import { apiClient } from "./client";
import {
  ReportMaster,
  ReportDetail,
  GetReportsParams,
  GetReportsResponse,
  CreateReportRequest,
  UpdateReportRequest,
  SaveLayoutRequest,
  GetTemplatesResponse,
  CreateTemplateRequest,
  ReportLayout,
} 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) => {
    const response = await apiClient.post<{
      success: boolean;
      data: { reportId: string };
      message: string;
    }>(`${BASE_URL}/${reportId}/copy`);
    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;
  },

  // 템플릿 생성
  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;
  },

  // 외부 DB 연결 목록 조회
  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;
  },

  // 이미지 업로드
  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;
  },
};
