import { apiClient } from "./client";

export interface ExcelMappingTemplate {
  id?: number;
  tableName: string;
  excelColumns: string[];
  excelColumnsHash: string;
  columnMappings: Record<string, string | null>; // { "엑셀컬럼": "시스템컬럼" }
  companyCode: string;
  createdDate?: string;
  updatedDate?: string;
}

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

/**
 * 엑셀 컬럼 구조로 매핑 템플릿 조회
 * 동일한 엑셀 컬럼 구조가 있으면 기존 매핑 반환
 */
export async function findMappingByColumns(
  tableName: string,
  excelColumns: string[]
): Promise<ApiResponse<ExcelMappingTemplate | null>> {
  try {
    const response = await apiClient.post("/excel-mapping/find", {
      tableName,
      excelColumns,
    });
    return response.data;
  } catch (error: any) {
    console.error("매핑 템플릿 조회 실패:", error);
    return {
      success: false,
      error: error.message || "매핑 템플릿 조회 실패",
    };
  }
}

/**
 * 매핑 템플릿 저장 (UPSERT)
 * 동일한 테이블+컬럼구조가 있으면 업데이트, 없으면 삽입
 */
export async function saveMappingTemplate(
  tableName: string,
  excelColumns: string[],
  columnMappings: Record<string, string | null>
): Promise<ApiResponse<ExcelMappingTemplate>> {
  try {
    const response = await apiClient.post("/excel-mapping/save", {
      tableName,
      excelColumns,
      columnMappings,
    });
    return response.data;
  } catch (error: any) {
    console.error("매핑 템플릿 저장 실패:", error);
    return {
      success: false,
      error: error.message || "매핑 템플릿 저장 실패",
    };
  }
}

/**
 * 테이블의 매핑 템플릿 목록 조회
 */
export async function getMappingTemplates(
  tableName: string
): Promise<ApiResponse<ExcelMappingTemplate[]>> {
  try {
    const response = await apiClient.get(
      `/excel-mapping/list/${encodeURIComponent(tableName)}`
    );
    return response.data;
  } catch (error: any) {
    console.error("매핑 템플릿 목록 조회 실패:", error);
    return {
      success: false,
      error: error.message || "매핑 템플릿 목록 조회 실패",
    };
  }
}

/**
 * 매핑 템플릿 삭제
 */
export async function deleteMappingTemplate(
  id: number
): Promise<ApiResponse<void>> {
  try {
    const response = await apiClient.delete(`/excel-mapping/${id}`);
    return response.data;
  } catch (error: any) {
    console.error("매핑 템플릿 삭제 실패:", error);
    return {
      success: false,
      error: error.message || "매핑 템플릿 삭제 실패",
    };
  }
}

