/**
 * 다중 테이블 엑셀 업로드 API 클라이언트
 */
import { apiClient } from "./client";

/** 테이블 계층 레벨 설정 */
export interface TableLevel {
  tableName: string;
  label: string;
  parentFkColumn?: string;
  parentRefColumn?: string;
  upsertMode: "upsert" | "insert";
  upsertKeyColumns?: string[];
  columns: ColumnDef[];
}

/** 컬럼 정의 */
export interface ColumnDef {
  dbColumn: string;
  excelHeader: string;
  required: boolean;
  defaultValue?: any;
}

/** 업로드 모드 정의 */
export interface UploadMode {
  id: string;
  label: string;
  description: string;
  activeLevels: number[];
}

/** 테이블 체인 설정 */
export interface TableChainConfig {
  id: string;
  name: string;
  description: string;
  levels: TableLevel[];
  uploadModes: UploadMode[];
}

/** 레벨별 결과 */
export interface LevelResult {
  tableName: string;
  inserted: number;
  updated: number;
}

/** 업로드 결과 */
export interface MultiTableUploadResult {
  success: boolean;
  results: LevelResult[];
  totalRows: number;
  errors: string[];
}

/**
 * 루트 테이블명으로 TableChainConfig를 자동 감지
 * DB FK 관계 + 컬럼 메타데이터를 분석하여 실시간 생성
 */
export async function autoDetectMultiTableConfig(
  rootTable: string,
  screenId?: number
): Promise<{ success: boolean; data?: TableChainConfig; message?: string }> {
  try {
    const params: Record<string, any> = { rootTable };
    if (screenId) params.screenId = screenId;

    const response = await apiClient.get("/data/multi-table/auto-detect", {
      params,
    });
    return response.data;
  } catch (error: any) {
    return {
      success: false,
      message: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 다중 테이블 엑셀 업로드 실행
 */
export async function uploadMultiTableExcel(params: {
  config: TableChainConfig;
  modeId: string;
  rows: Record<string, any>[];
}): Promise<{ success: boolean; data?: MultiTableUploadResult; message?: string }> {
  try {
    const response = await apiClient.post("/data/multi-table/upload", params);
    return response.data;
  } catch (error: any) {
    return {
      success: false,
      message: error.response?.data?.message || error.message,
    };
  }
}
