import { apiClient } from "./client";
import {
  ReportDetail,
  GetReportsParams,
  GetReportsResponse,
  GetReportsByMenuResponse,
  CreateReportRequest,
  UpdateReportRequest,
  SaveLayoutRequest,
  GetTemplatesResponse,
  CreateTemplateRequest,
  ReportLayout,
  VisualQuery,
} from "@/types/report";

const BASE_URL = "/admin/reports";

export const reportApi = {
  getReports: async (params: GetReportsParams) => {
    const response = await apiClient.get<{
      success: boolean;
      data: GetReportsResponse;
    }>(BASE_URL, { params });
    return response.data;
  },

  getReportById: async (reportId: string) => {
    const response = await apiClient.get<{
      success: boolean;
      data: ReportDetail;
    }>(`${BASE_URL}/${reportId}`);
    return response.data;
  },

  createReport: async (data: CreateReportRequest) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { reportId: string };
      message: string;
    }>(BASE_URL, data);
    return response.data;
  },

  updateReport: async (reportId: string, data: UpdateReportRequest) => {
    const response = await apiClient.put<{
      success: boolean;
      message: string;
    }>(`${BASE_URL}/${reportId}`, data);
    return response.data;
  },

  deleteReport: async (reportId: string) => {
    const response = await apiClient.delete<{
      success: boolean;
      message: string;
    }>(`${BASE_URL}/${reportId}`);
    return response.data;
  },

  copyReport: async (reportId: string, newName?: string) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { reportId: string };
      message: string;
    }>(`${BASE_URL}/${reportId}/copy`, newName ? { newName } : {});
    return response.data;
  },

  getLayout: async (reportId: string) => {
    const response = await apiClient.get<{
      success: boolean;
      data: ReportLayout;
    }>(`${BASE_URL}/${reportId}/layout`);
    return response.data;
  },

  saveLayout: async (reportId: string, data: SaveLayoutRequest) => {
    const response = await apiClient.put<{
      success: boolean;
      message: string;
    }>(`${BASE_URL}/${reportId}/layout`, data);
    return response.data;
  },

  getTemplates: async () => {
    const response = await apiClient.get<{
      success: boolean;
      data: GetTemplatesResponse;
    }>(`${BASE_URL}/templates`);
    return response.data;
  },

  getCategories: async () => {
    const response = await apiClient.get<{
      success: boolean;
      data: string[];
    }>(`${BASE_URL}/categories`);
    return response.data;
  },

  createTemplate: async (data: CreateTemplateRequest) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { templateId: string };
      message: string;
    }>(`${BASE_URL}/templates`, data);
    return response.data;
  },

  deleteTemplate: async (templateId: string) => {
    const response = await apiClient.delete<{
      success: boolean;
      message: string;
    }>(`${BASE_URL}/templates/${templateId}`);
    return response.data;
  },

  executeQuery: async (
    reportId: string,
    queryId: string,
    parameters: Record<string, any>,
    sqlQuery?: string,
    externalConnectionId?: number | null,
  ) => {
    const response = await apiClient.post<{
      success: boolean;
      data: {
        fields: string[];
        rows: any[];
      };
    }>(`${BASE_URL}/${reportId}/queries/${queryId}/execute`, {
      parameters,
      sqlQuery,
      externalConnectionId,
    });
    return response.data;
  },

  getExternalConnections: async () => {
    const response = await apiClient.get<{
      success: boolean;
      data: any[];
    }>(`${BASE_URL}/external-connections`);
    return response.data;
  },

  saveAsTemplate: async (
    reportId: string,
    data: {
      templateNameKor: string;
      templateNameEng?: string;
      description?: string;
    },
  ) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { templateId: string };
      message: string;
    }>(`${BASE_URL}/${reportId}/save-as-template`, data);
    return response.data;
  },

  createTemplateFromLayout: async (data: {
    templateNameKor: string;
    templateNameEng?: string;
    templateType?: string;
    description?: string;
    layoutConfig: {
      width: number;
      height: number;
      orientation: string;
      margins: {
        top: number;
        bottom: number;
        left: number;
        right: number;
      };
      components: any[];
    };
    defaultQueries?: Array<{
      name: string;
      type: "MASTER" | "DETAIL";
      sqlQuery: string;
      parameters: string[];
      externalConnectionId?: number | null;
      displayOrder?: number;
    }>;
  }) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { templateId: string };
      message: string;
    }>(`${BASE_URL}/templates/create-from-layout`, data);
    return response.data;
  },

  getReportsByMenuObjid: async (menuObjid: number) => {
    const response = await apiClient.get<{
      success: boolean;
      data: GetReportsByMenuResponse;
    }>(`${BASE_URL}/by-menu/${menuObjid}`);
    return response.data;
  },

  // ─── 비주얼 쿼리 빌더 API ─────────────────────────────────────────────────

  getSchemaTableList: async () => {
    const response = await apiClient.get<{
      success: boolean;
      data: Array<{ table_name: string; table_type: string }>;
    }>(`${BASE_URL}/schema/tables`);
    return response.data;
  },

  getSchemaTableColumns: async (tableName: string) => {
    const response = await apiClient.get<{
      success: boolean;
      data: Array<{ column_name: string; data_type: string; is_nullable: string }>;
    }>(`${BASE_URL}/schema/tables/${encodeURIComponent(tableName)}/columns`);
    return response.data;
  },

  getSchemaTableForeignKeys: async (tableName: string) => {
    const response = await apiClient.get<{
      success: boolean;
      data: Array<{
        constraint_name: string;
        columns: string[];
        foreign_table: string;
        foreign_columns: string[];
      }>;
    }>(`${BASE_URL}/schema/tables/${encodeURIComponent(tableName)}/foreign-keys`);
    return response.data;
  },

  previewVisualQuery: async (visualQuery: VisualQuery) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { fields: string[]; rows: any[]; sql: string };
    }>(`${BASE_URL}/schema/preview`, { visualQuery });
    return response.data;
  },

  uploadImage: async (file: File) => {
    const formData = new FormData();
    formData.append("image", file);

    const response = await apiClient.post<{
      success: boolean;
      data: {
        fileName: string;
        fileUrl: string;
        originalName: string;
        size: number;
        mimeType: string;
      };
      message?: string;
    }>(`${BASE_URL}/upload-image`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    return response.data;
  },
};
