import api, { PageResponse, unwrap } from './request';

export interface UploadTemplateResp {
  templateId: number;
  templateCode: string;
  templateName: string;
  category: string;
  targetTable: string;
  companyCode?: string;
  headerRow: number;
  dataStartRow: number;
  sheetIndex: number;
  sheetName?: string;
  batchSize: number;
  isActive: string;
  description?: string;
  updatedAt?: string;
}

export interface UploadTemplateDetailResp extends UploadTemplateResp {
  columns: UploadTemplateColumnVO[];
}

export interface UploadTemplateColumnVO {
  columnId?: number;
  templateId?: number;
  sortOrder: number;
  sourceType: string;
  sourceColumn?: string;
  sourceHeader?: string;
  targetField: string;
  targetType: string;
  transformRule?: string;
  transformParam?: string;
  dateFormat?: string;
  numberDivide?: number;
  numberMultiply?: number;
  fixedValue?: string;
  defaultValue?: string;
  lookupTable?: string;
  lookupSourceField?: string;
  lookupTargetField?: string;
  codeMapGroup?: string;
  isRequired?: string;
  validationRegex?: string;
  validationMessage?: string;
  description?: string;
}

export interface UploadTemplateQueryParams {
  category?: string;
  companyCode?: string;
  isActive?: string;
  searchKeyword?: string;
  pageNum?: number;
  pageSize?: number;
}

export interface UploadTemplateSaveReq {
  templateCode: string;
  templateName: string;
  category: string;
  targetTable: string;
  companyCode?: string;
  headerRow?: number;
  dataStartRow?: number;
  sheetIndex?: number;
  sheetName?: string;
  batchSize?: number;
  isActive?: string;
  description?: string;
}

export interface UploadHistoryResp {
  historyId: number;
  templateId: number;
  fileName: string;
  totalCount: number;
  successCount: number;
  errorCount: number;
  skipCount: number;
  uploadedBy?: string;
  uploadedAt?: string;
  durationSec?: number;
}

export interface UploadResultResp {
  totalCount: number;
  successCount: number;
  errorCount: number;
  skipCount: number;
  errorFileId?: number;
  durationSec?: number;
  errors?: {
    rowNumber: number;
    fieldName?: string;
    value?: string;
    errorMessage: string;
  }[];
}

export interface PreviewRowResp {
  rowNumber: number;
  [field: string]: unknown;
}

/** 샘플 엑셀 헤더 추출 응답 */
export interface ExcelHeaderResp {
  columns: string[];           // ['A','B','C',...]
  headers: string[];           // ['증권번호','설계사명',...]
  samples: string[][];         // 첫 N행
}

/** target_table 별 사용 가능한 컬럼 메타 */
export interface TargetFieldMeta {
  field: string;       // policy_no
  label: string;       // 증권번호
  type: string;        // STRING/NUMBER/DECIMAL/DATE/INTEGER
  required: boolean;
}

export const uploadTemplateApi = {
  list: (params: UploadTemplateQueryParams) =>
    unwrap<PageResponse<UploadTemplateResp>>(api.get('/api/upload-templates', { params })),

  detail: (id: number) =>
    unwrap<UploadTemplateDetailResp>(api.get(`/api/upload-templates/${id}`)),

  create: (req: UploadTemplateSaveReq) =>
    unwrap<number>(api.post('/api/upload-templates', req)),

  update: (id: number, req: UploadTemplateSaveReq) =>
    unwrap<void>(api.put(`/api/upload-templates/${id}`, req)),

  remove: (id: number) =>
    unwrap<void>(api.delete(`/api/upload-templates/${id}`)),

  getColumns: (id: number) =>
    unwrap<UploadTemplateColumnVO[]>(api.get(`/api/upload-templates/${id}/columns`)),

  saveColumns: (id: number, columns: UploadTemplateColumnVO[]) =>
    unwrap<void>(api.put(`/api/upload-templates/${id}/columns`, columns)),

  history: (id: number) =>
    unwrap<UploadHistoryResp[]>(api.get(`/api/upload-templates/${id}/history`)),

  preview: (templateCode: string, file: File) => {
    const fd = new FormData();
    fd.append('file', file);
    return unwrap<PreviewRowResp[]>(
      api.post(`/api/upload-templates/${templateCode}/preview`, fd, {
        headers: { 'Content-Type': 'multipart/form-data' },
      }),
    );
  },

  upload: (templateCode: string, file: File) => {
    const fd = new FormData();
    fd.append('file', file);
    return unwrap<UploadResultResp>(
      api.post(`/api/upload/${templateCode}`, fd, {
        headers: { 'Content-Type': 'multipart/form-data' },
      }),
    );
  },

  /** 샘플 엑셀 → 헤더 + 미리보기 행 자동 추출 (등록 전 매핑 자동 채우기용) */
  extractHeaders: (file: File, headerRow = 1, sheetIndex = 0, previewRows = 5) => {
    const fd = new FormData();
    fd.append('file', file);
    return unwrap<ExcelHeaderResp>(
      api.post('/api/upload-templates/excel-headers', fd, {
        headers: { 'Content-Type': 'multipart/form-data' },
        params: { headerRow, sheetIndex, previewRows },
      }),
    );
  },

  /** target_table 별 사용 가능한 DB 컬럼 (target_field Select 옵션) */
  targetFields: (targetTable: string) =>
    unwrap<TargetFieldMeta[]>(api.get(`/api/upload-templates/target-fields/${targetTable}`)),

  /** 사용 가능한 target_table 목록 */
  targetTables: () =>
    unwrap<string[]>(api.get('/api/upload-templates/target-tables')),
};
