/**
 * ECR(Engineering Change Request) 관리 API 클라이언트
 *  - 백엔드: backend-node/src/routes/ecrMngRoutes.ts
 */
import { apiClient } from "./client";

export interface EcrItem {
  objid: string;
  ecr_no: string;
  product_name?: string;
  product_objid?: string;
  upg_no?: string;
  part_no?: string;
  part_name?: string;
  part_objid?: string;
  request_cd?: string;
  request_name?: string;
  title: string;
  writer?: string;
  writer_name?: string;
  status_cd?: string;
  status_name?: string;
  check_user_id?: string;
  check_name?: string;
  before_contents?: string;
  after_contents?: string;
  reg_date?: string;
  check_date?: string;
  /* ilshin 운영 ecr_mng 동기화로 추가된 컬럼 */
  project_no?: string;
  customer_cd?: string;
  equip_name?: string;
  design_dept?: string;
  unit_cd?: string;
  memo?: string;
  check_result?: string;
}

export interface EcrListResponse {
  success: boolean;
  list: EcrItem[];
  pagination: { page: number; pageSize: number; total: number; totalPages: number };
}

export interface EcrListParams {
  year?: string;
  productCode?: string;
  requestCode?: string;
  writer?: string;
  statusCode?: string;
  page?: number;
  pageSize?: number;
}

export const ecrMngApi = {
  list: async (params: EcrListParams = {}): Promise<EcrListResponse> => {
    const { data } = await apiClient.get("/ecr", { params });
    return data;
  },

  detail: async (objId: string | number): Promise<EcrItem> => {
    const { data } = await apiClient.get(`/ecr/${objId}`);
    return data.data;
  },

  /** 등록/수정 (objId 가 있으면 update) */
  merge: async (payload: {
    objId?: string | number;
    title: string;
    product_objid?: string | number | null;
    part_objid?: string | number | null;
    request_codeArr?: string;
    before_contents?: string;
    after_contents?: string;
  }): Promise<{ objid: string; ecr_no: string; status_cd: string }> => {
    const { data } = await apiClient.post("/ecr", payload);
    return data.data;
  },

  /** 조치완료 — status → 0000102 */
  complete: async (objId: string | number, after_contents: string) => {
    const { data } = await apiClient.post(`/ecr/${objId}/complete`, { after_contents });
    return data;
  },

  remove: async (objIds: string[]) => {
    const { data } = await apiClient.delete("/ecr", { data: { objIds } });
    return data;
  },

  // 옵션 — 드롭다운/체크박스용
  writerOptions: async (): Promise<Array<{ value: string; label: string }>> =>
    (await apiClient.get("/ecr/options/writers")).data.data,
  productOptions: async (): Promise<Array<{ value: string; label: string }>> =>
    (await apiClient.get("/ecr/options/products")).data.data,
  partOptions: async (): Promise<Array<{ value: string; label: string }>> =>
    (await apiClient.get("/ecr/options/parts")).data.data,
  /** parentCodeId='0000090' (요청코드) / '0000099' (상태) */
  commCodeOptions: async (parentCodeId: string): Promise<Array<{ value: string; label: string }>> =>
    (await apiClient.get(`/ecr/options/codes/${parentCodeId}`)).data.data,
};
