/**
 * 자동 입력 (Auto-Fill) API 클라이언트
 */

import { apiClient } from "./client";

// =====================================================
// 타입 정의
// =====================================================

export interface AutoFillMapping {
  mappingId?: number;
  sourceColumn: string;
  targetField: string;
  targetLabel?: string;
  isEditable?: string;
  isRequired?: string;
  defaultValue?: string;
  sortOrder?: number;
}

export interface AutoFillGroup {
  groupId?: number;
  groupCode: string;
  groupName: string;
  description?: string;
  masterTable: string;
  masterValueColumn: string;
  masterLabelColumn?: string;
  companyCode?: string;
  isActive?: string;
  createdDate?: string;
  updatedDate?: string;
  mappingCount?: number;
  mappings?: AutoFillMapping[];
}

export interface AutoFillOption {
  value: string;
  label: string;
}

export interface AutoFillDataResponse {
  data: Record<string, any>;
  mappings: Array<{
    targetField: string;
    targetLabel: string;
    value: any;
    isEditable: boolean;
    isRequired: boolean;
  }>;
}

// =====================================================
// API 함수
// =====================================================

/**
 * 자동 입력 그룹 목록 조회
 */
export async function getAutoFillGroups(isActive?: string): Promise<{
  success: boolean;
  data?: AutoFillGroup[];
  error?: string;
}> {
  try {
    const params = new URLSearchParams();
    if (isActive) params.append("isActive", isActive);

    const response = await apiClient.get(`/cascading-auto-fill/groups?${params.toString()}`);
    return response.data;
  } catch (error: any) {
    console.error("자동 입력 그룹 목록 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 자동 입력 그룹 상세 조회 (매핑 포함)
 */
export async function getAutoFillGroupDetail(groupCode: string): Promise<{
  success: boolean;
  data?: AutoFillGroup;
  error?: string;
}> {
  try {
    const response = await apiClient.get(`/cascading-auto-fill/groups/${groupCode}`);
    return response.data;
  } catch (error: any) {
    console.error("자동 입력 그룹 상세 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 자동 입력 그룹 생성
 */
export async function createAutoFillGroup(data: {
  groupCode: string;
  groupName: string;
  description?: string;
  masterTable: string;
  masterValueColumn: string;
  masterLabelColumn?: string;
  mappings?: AutoFillMapping[];
}): Promise<{
  success: boolean;
  data?: AutoFillGroup;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.post("/cascading-auto-fill/groups", data);
    return response.data;
  } catch (error: any) {
    console.error("자동 입력 그룹 생성 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 자동 입력 그룹 수정
 */
export async function updateAutoFillGroup(
  groupCode: string,
  data: Partial<AutoFillGroup> & { mappings?: AutoFillMapping[] }
): Promise<{
  success: boolean;
  data?: AutoFillGroup;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.put(`/cascading-auto-fill/groups/${groupCode}`, data);
    return response.data;
  } catch (error: any) {
    console.error("자동 입력 그룹 수정 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 자동 입력 그룹 삭제
 */
export async function deleteAutoFillGroup(groupCode: string): Promise<{
  success: boolean;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.delete(`/cascading-auto-fill/groups/${groupCode}`);
    return response.data;
  } catch (error: any) {
    console.error("자동 입력 그룹 삭제 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 마스터 옵션 목록 조회
 */
export async function getAutoFillMasterOptions(groupCode: string): Promise<{
  success: boolean;
  data?: AutoFillOption[];
  error?: string;
}> {
  try {
    const response = await apiClient.get(`/cascading-auto-fill/options/${groupCode}`);
    return response.data;
  } catch (error: any) {
    console.error("마스터 옵션 목록 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 자동 입력 데이터 조회
 * 마스터 값 선택 시 자동으로 입력할 데이터 조회
 */
export async function getAutoFillData(
  groupCode: string,
  masterValue: string
): Promise<{
  success: boolean;
  data?: Record<string, any>;
  mappings?: AutoFillDataResponse["mappings"];
  error?: string;
}> {
  try {
    const response = await apiClient.get(
      `/cascading-auto-fill/data/${groupCode}?masterValue=${encodeURIComponent(masterValue)}`
    );
    return response.data;
  } catch (error: any) {
    console.error("자동 입력 데이터 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

// 편의를 위한 네임스페이스 export
export const cascadingAutoFillApi = {
  getGroups: getAutoFillGroups,
  getGroupDetail: getAutoFillGroupDetail,
  createGroup: createAutoFillGroup,
  updateGroup: updateAutoFillGroup,
  deleteGroup: deleteAutoFillGroup,
  getMasterOptions: getAutoFillMasterOptions,
  getData: getAutoFillData,
};

