import { apiClient } from "./client";

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

export interface CategoryValueCascadingGroup {
  group_id: number;
  relation_code: string;
  relation_name: string;
  description?: string;
  parent_table_name: string;
  parent_column_name: string;
  parent_menu_objid?: number;
  child_table_name: string;
  child_column_name: string;
  child_menu_objid?: number;
  clear_on_parent_change?: string;
  show_group_label?: string;
  empty_parent_message?: string;
  no_options_message?: string;
  company_code: string;
  is_active?: string;
  created_by?: string;
  created_date?: string;
  updated_by?: string;
  updated_date?: string;
  // 상세 조회 시 포함
  mappings?: CategoryValueCascadingMapping[];
  mappingsByParent?: Record<string, { childValueCode: string; childValueLabel: string; displayOrder: number }[]>;
}

export interface CategoryValueCascadingMapping {
  mapping_id?: number;
  parent_value_code: string;
  parent_value_label?: string;
  child_value_code: string;
  child_value_label?: string;
  display_order?: number;
}

export interface CategoryValueCascadingGroupInput {
  relationCode: string;
  relationName: string;
  description?: string;
  parentTableName: string;
  parentColumnName: string;
  parentMenuObjid?: number;
  childTableName: string;
  childColumnName: string;
  childMenuObjid?: number;
  clearOnParentChange?: boolean;
  showGroupLabel?: boolean;
  emptyParentMessage?: string;
  noOptionsMessage?: string;
}

export interface CategoryValueCascadingMappingInput {
  parentValueCode: string;
  parentValueLabel?: string;
  childValueCode: string;
  childValueLabel?: string;
  displayOrder?: number;
}

export interface CategoryValueCascadingOption {
  value: string;
  label: string;
  parent_value?: string;
  parent_label?: string;
  display_order?: number;
}

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

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

/**
 * 카테고리 값 연쇄관계 그룹 상세 조회
 */
export const getCategoryValueCascadingGroupById = async (groupId: number) => {
  try {
    const response = await apiClient.get(`/category-value-cascading/groups/${groupId}`);
    return response.data;
  } catch (error: any) {
    console.error("카테고리 값 연쇄관계 그룹 상세 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

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

/**
 * 카테고리 값 연쇄관계 그룹 생성
 */
export const createCategoryValueCascadingGroup = async (data: CategoryValueCascadingGroupInput) => {
  try {
    const response = await apiClient.post("/category-value-cascading/groups", data);
    return response.data;
  } catch (error: any) {
    console.error("카테고리 값 연쇄관계 그룹 생성 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 카테고리 값 연쇄관계 그룹 수정
 */
export const updateCategoryValueCascadingGroup = async (
  groupId: number,
  data: Partial<CategoryValueCascadingGroupInput> & { isActive?: boolean }
) => {
  try {
    const response = await apiClient.put(`/category-value-cascading/groups/${groupId}`, data);
    return response.data;
  } catch (error: any) {
    console.error("카테고리 값 연쇄관계 그룹 수정 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 카테고리 값 연쇄관계 그룹 삭제
 */
export const deleteCategoryValueCascadingGroup = async (groupId: number) => {
  try {
    const response = await apiClient.delete(`/category-value-cascading/groups/${groupId}`);
    return response.data;
  } catch (error: any) {
    console.error("카테고리 값 연쇄관계 그룹 삭제 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 매핑 일괄 저장
 */
export const saveCategoryValueCascadingMappings = async (
  groupId: number,
  mappings: CategoryValueCascadingMappingInput[]
) => {
  try {
    const response = await apiClient.post(`/category-value-cascading/groups/${groupId}/mappings`, { mappings });
    return response.data;
  } catch (error: any) {
    console.error("카테고리 값 연쇄관계 매핑 저장 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 연쇄 옵션 조회 (실제 드롭다운에서 사용)
 * 다중 부모값 지원
 */
export const getCategoryValueCascadingOptions = async (
  code: string,
  parentValue: string | string[]
): Promise<{ success: boolean; data?: CategoryValueCascadingOption[]; showGroupLabel?: boolean; error?: string }> => {
  try {
    let url: string;
    
    if (Array.isArray(parentValue)) {
      if (parentValue.length === 0) {
        return { success: true, data: [] };
      }
      const parentValuesParam = parentValue.join(',');
      url = `/category-value-cascading/options/${code}?parentValues=${encodeURIComponent(parentValuesParam)}`;
    } else {
      url = `/category-value-cascading/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 getCategoryValueCascadingParentOptions = async (code: string) => {
  try {
    const response = await apiClient.get(`/category-value-cascading/parent-options/${code}`);
    return response.data;
  } catch (error: any) {
    console.error("부모 카테고리 값 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

/**
 * 자식 카테고리 값 목록 조회 (매핑 설정 UI용)
 */
export const getCategoryValueCascadingChildOptions = async (code: string) => {
  try {
    const response = await apiClient.get(`/category-value-cascading/child-options/${code}`);
    return response.data;
  } catch (error: any) {
    console.error("자식 카테고리 값 조회 실패:", error);
    return { success: false, error: error.message };
  }
};

// ============================================
// API 객체 export
// ============================================

export const categoryValueCascadingApi = {
  // 그룹 CRUD
  getGroups: getCategoryValueCascadingGroups,
  getGroupById: getCategoryValueCascadingGroupById,
  getByCode: getCategoryValueCascadingByCode,
  createGroup: createCategoryValueCascadingGroup,
  updateGroup: updateCategoryValueCascadingGroup,
  deleteGroup: deleteCategoryValueCascadingGroup,
  
  // 매핑
  saveMappings: saveCategoryValueCascadingMappings,
  
  // 옵션 조회
  getOptions: getCategoryValueCascadingOptions,
  getParentOptions: getCategoryValueCascadingParentOptions,
  getChildOptions: getCategoryValueCascadingChildOptions,
};

