/**
 * 조건부 연쇄 (Conditional Cascading) API 클라이언트
 */

import { apiClient } from "./client";

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

export interface CascadingCondition {
  conditionId?: number;
  relationType: string; // "RELATION" | "HIERARCHY"
  relationCode: string;
  conditionName: string;
  conditionField: string;
  conditionOperator: string; // "EQ" | "NEQ" | "CONTAINS" | "IN" | "GT" | "LT" 등
  conditionValue: string;
  filterColumn: string;
  filterValues: string; // 콤마로 구분된 값들
  priority?: number;
  companyCode?: string;
  isActive?: string;
  createdDate?: string;
  updatedDate?: string;
}

// 연산자 목록
export const CONDITION_OPERATORS = [
  { value: "EQ", label: "같음 (=)" },
  { value: "NEQ", label: "같지 않음 (!=)" },
  { value: "CONTAINS", label: "포함" },
  { value: "NOT_CONTAINS", label: "포함하지 않음" },
  { value: "STARTS_WITH", label: "시작" },
  { value: "ENDS_WITH", label: "끝" },
  { value: "IN", label: "목록에 포함" },
  { value: "NOT_IN", label: "목록에 미포함" },
  { value: "GT", label: "보다 큼 (>)" },
  { value: "GTE", label: "보다 크거나 같음 (>=)" },
  { value: "LT", label: "보다 작음 (<)" },
  { value: "LTE", label: "보다 작거나 같음 (<=)" },
  { value: "IS_NULL", label: "비어있음" },
  { value: "IS_NOT_NULL", label: "비어있지 않음" },
];

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

/**
 * 조건부 연쇄 규칙 목록 조회
 */
export async function getConditions(params?: {
  isActive?: string;
  relationCode?: string;
  relationType?: string;
}): Promise<{
  success: boolean;
  data?: CascadingCondition[];
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();
    if (params?.isActive) searchParams.append("isActive", params.isActive);
    if (params?.relationCode) searchParams.append("relationCode", params.relationCode);
    if (params?.relationType) searchParams.append("relationType", params.relationType);

    const response = await apiClient.get(`/cascading-conditions?${searchParams.toString()}`);
    return response.data;
  } catch (error: any) {
    console.error("조건부 연쇄 규칙 목록 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 조건부 연쇄 규칙 상세 조회
 */
export async function getConditionDetail(conditionId: number): Promise<{
  success: boolean;
  data?: CascadingCondition;
  error?: string;
}> {
  try {
    const response = await apiClient.get(`/cascading-conditions/${conditionId}`);
    return response.data;
  } catch (error: any) {
    console.error("조건부 연쇄 규칙 상세 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 조건부 연쇄 규칙 생성
 */
export async function createCondition(data: Omit<CascadingCondition, "conditionId">): Promise<{
  success: boolean;
  data?: CascadingCondition;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.post("/cascading-conditions", data);
    return response.data;
  } catch (error: any) {
    console.error("조건부 연쇄 규칙 생성 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 조건부 연쇄 규칙 수정
 */
export async function updateCondition(
  conditionId: number,
  data: Partial<CascadingCondition>
): Promise<{
  success: boolean;
  data?: CascadingCondition;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.put(`/cascading-conditions/${conditionId}`, data);
    return response.data;
  } catch (error: any) {
    console.error("조건부 연쇄 규칙 수정 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 조건부 연쇄 규칙 삭제
 */
export async function deleteCondition(conditionId: number): Promise<{
  success: boolean;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.delete(`/cascading-conditions/${conditionId}`);
    return response.data;
  } catch (error: any) {
    console.error("조건부 연쇄 규칙 삭제 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 조건에 따른 필터링된 옵션 조회
 */
export async function getFilteredOptions(
  relationCode: string,
  params: {
    conditionFieldValue?: string;
    parentValue?: string;
  }
): Promise<{
  success: boolean;
  data?: Array<{ value: string; label: string }>;
  appliedCondition?: { conditionId: number; conditionName: string } | null;
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();
    if (params.conditionFieldValue) searchParams.append("conditionFieldValue", params.conditionFieldValue);
    if (params.parentValue) searchParams.append("parentValue", params.parentValue);

    const response = await apiClient.get(
      `/cascading-conditions/filtered-options/${relationCode}?${searchParams.toString()}`
    );
    return response.data;
  } catch (error: any) {
    console.error("조건부 필터링 옵션 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

// 편의를 위한 네임스페이스 export
export const cascadingConditionApi = {
  getList: getConditions,
  getDetail: getConditionDetail,
  create: createCondition,
  update: updateCondition,
  delete: deleteCondition,
  getFilteredOptions,
};

