/**
 * 상호 배제 (Mutual Exclusion) API 클라이언트
 */

import { apiClient } from "./client";

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

export interface MutualExclusion {
  exclusionId?: number;
  exclusionCode: string;
  exclusionName: string;
  fieldNames: string; // 콤마로 구분된 필드명 (예: "source_warehouse,target_warehouse")
  sourceTable: string;
  valueColumn: string;
  labelColumn?: string;
  exclusionType?: string; // "SAME_VALUE"
  errorMessage?: string;
  companyCode?: string;
  isActive?: string;
  createdDate?: string;
}

// 배제 타입 목록
export const EXCLUSION_TYPES = [
  { value: "SAME_VALUE", label: "동일 값 배제" },
  { value: "RELATED", label: "관련 값 배제 (예정)" },
];

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

/**
 * 상호 배제 규칙 목록 조회
 */
export async function getExclusions(isActive?: string): Promise<{
  success: boolean;
  data?: MutualExclusion[];
  error?: string;
}> {
  try {
    const params = new URLSearchParams();
    if (isActive) params.append("isActive", isActive);

    const response = await apiClient.get(`/cascading-exclusions?${params.toString()}`);
    return response.data;
  } catch (error: any) {
    console.error("상호 배제 규칙 목록 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 상호 배제 규칙 상세 조회
 */
export async function getExclusionDetail(exclusionId: number): Promise<{
  success: boolean;
  data?: MutualExclusion;
  error?: string;
}> {
  try {
    const response = await apiClient.get(`/cascading-exclusions/${exclusionId}`);
    return response.data;
  } catch (error: any) {
    console.error("상호 배제 규칙 상세 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 상호 배제 규칙 생성
 */
export async function createExclusion(data: Omit<MutualExclusion, "exclusionId">): Promise<{
  success: boolean;
  data?: MutualExclusion;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.post("/cascading-exclusions", data);
    return response.data;
  } catch (error: any) {
    console.error("상호 배제 규칙 생성 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 상호 배제 규칙 수정
 */
export async function updateExclusion(
  exclusionId: number,
  data: Partial<MutualExclusion>
): Promise<{
  success: boolean;
  data?: MutualExclusion;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.put(`/cascading-exclusions/${exclusionId}`, data);
    return response.data;
  } catch (error: any) {
    console.error("상호 배제 규칙 수정 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 상호 배제 규칙 삭제
 */
export async function deleteExclusion(exclusionId: number): Promise<{
  success: boolean;
  message?: string;
  error?: string;
}> {
  try {
    const response = await apiClient.delete(`/cascading-exclusions/${exclusionId}`);
    return response.data;
  } catch (error: any) {
    console.error("상호 배제 규칙 삭제 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 상호 배제 검증
 */
export async function validateExclusion(
  exclusionCode: string,
  fieldValues: Record<string, string>
): Promise<{
  success: boolean;
  data?: {
    isValid: boolean;
    errorMessage: string | null;
    conflictingFields: string[];
  };
  error?: string;
}> {
  try {
    const response = await apiClient.post(`/cascading-exclusions/validate/${exclusionCode}`, {
      fieldValues,
    });
    return response.data;
  } catch (error: any) {
    console.error("상호 배제 검증 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

/**
 * 배제된 옵션 조회 (다른 필드에서 선택한 값 제외)
 */
export async function getExcludedOptions(
  exclusionCode: string,
  params: {
    currentField?: string;
    selectedValues?: string; // 콤마로 구분된 값들
  }
): Promise<{
  success: boolean;
  data?: Array<{ value: string; label: string }>;
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();
    if (params.currentField) searchParams.append("currentField", params.currentField);
    if (params.selectedValues) searchParams.append("selectedValues", params.selectedValues);

    const response = await apiClient.get(
      `/cascading-exclusions/options/${exclusionCode}?${searchParams.toString()}`
    );
    return response.data;
  } catch (error: any) {
    console.error("배제된 옵션 조회 실패:", error);
    return {
      success: false,
      error: error.response?.data?.message || error.message,
    };
  }
}

// 편의를 위한 네임스페이스 export
export const mutualExclusionApi = {
  getList: getExclusions,
  getDetail: getExclusionDetail,
  create: createExclusion,
  update: updateExclusion,
  delete: deleteExclusion,
  validate: validateExclusion,
  getExcludedOptions,
};

