import { apiClient } from "./client";

export interface CascadingRelation {
  relation_id: number;
  relation_code: string;
  relation_name: string;
  description?: string;
  parent_table: string;
  parent_value_column: string;
  parent_label_column?: string;
  child_table: string;
  child_filter_column: string;
  child_value_column: string;
  child_label_column: string;
  child_order_column?: string;
  child_order_direction?: string;
  empty_parent_message?: string;
  no_options_message?: string;
  loading_message?: string;
  clear_on_parent_change?: string;
  company_code: string;
  is_active?: string;
  created_by?: string;
  created_date?: string;
  updated_by?: string;
  updated_date?: string;
}

export interface CascadingRelationCreateInput {
  relationCode: string;
  relationName: string;
  description?: string;
  parentTable: string;
  parentValueColumn: string;
  parentLabelColumn?: string;
  childTable: string;
  childFilterColumn: string;
  childValueColumn: string;
  childLabelColumn: string;
  childOrderColumn?: string;
  childOrderDirection?: string;
  emptyParentMessage?: string;
  noOptionsMessage?: string;
  loadingMessage?: string;
  clearOnParentChange?: boolean;
}

export interface CascadingRelationUpdateInput extends Partial<CascadingRelationCreateInput> {
  isActive?: boolean;
}

export interface CascadingOption {
  value: string;
  label: string;
  parent_value?: string; // 다중 부모 선택 시 어떤 부모에 속하는지 구분용
}

/**
 * 연쇄 관계 목록 조회
 */
export const getCascadingRelations = async (isActive?: string) => {
  try {
    const params = new URLSearchParams();
    if (isActive !== undefined) {
      params.append("isActive", isActive);
    }
    const response = await apiClient.get(`/cascading-relations?${params.toString()}`);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 관계 목록 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 관계 상세 조회 (ID)
 */
export const getCascadingRelationById = async (id: number) => {
  try {
    const response = await apiClient.get(`/cascading-relations/${id}`);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 관계 상세 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 관계 코드로 조회
 */
export const getCascadingRelationByCode = async (code: string) => {
  try {
    const response = await apiClient.get(`/cascading-relations/code/${code}`);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 관계 코드 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 관계로 자식 옵션 조회
 * 단일 부모값 또는 다중 부모값 지원
 */
export const getCascadingOptions = async (
  code: string, 
  parentValue: string | string[]
): Promise<{ success: boolean; data?: CascadingOption[]; error?: string }> => {
  try {
    let url: string;
    
    if (Array.isArray(parentValue)) {
      // 다중 부모값: parentValues 파라미터 사용
      if (parentValue.length === 0) {
        return { success: true, data: [] };
      }
      const parentValuesParam = parentValue.join(',');
      url = `/cascading-relations/options/${code}?parentValues=${encodeURIComponent(parentValuesParam)}`;
    } else {
      // 단일 부모값: 기존 호환
      url = `/cascading-relations/options/${code}?parentValue=${encodeURIComponent(parentValue)}`;
    }
    
    const response = await apiClient.get(url);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 옵션 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 관계 생성
 */
export const createCascadingRelation = async (data: CascadingRelationCreateInput) => {
  try {
    const response = await apiClient.post("/cascading-relations", data);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 관계 생성 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 관계 수정
 */
export const updateCascadingRelation = async (id: number, data: CascadingRelationUpdateInput) => {
  try {
    const response = await apiClient.put(`/cascading-relations/${id}`, data);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 관계 수정 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 관계 삭제
 */
export const deleteCascadingRelation = async (id: number) => {
  try {
    const response = await apiClient.delete(`/cascading-relations/${id}`);
    return response.data;
  } catch (error: any) {
    console.error("연쇄 관계 삭제 실패:", error);
    return { success: false, error: error.message };
  }
};

export const cascadingRelationApi = {
  getList: getCascadingRelations,
  getById: getCascadingRelationById,
  getByCode: getCascadingRelationByCode,
  getOptions: getCascadingOptions,
  create: createCascadingRelation,
  update: updateCascadingRelation,
  delete: deleteCascadingRelation,
};

