import { apiClient } from "@/lib/api/client";

export interface PaginatedResponse { success: boolean; data: any[]; totalCount: number; page: number; pageSize: number; }

export async function getWorkInstructionList(params?: Record<string, any>) {
  const res = await apiClient.get("/work-instruction/list", { params });
  return res.data as { success: boolean; data: any[]; totalCount?: number; page?: number; pageSize?: number };
}

export async function previewWorkInstructionNo() {
  const res = await apiClient.get("/work-instruction/preview-no");
  return res.data as { success: boolean; instructionNo: string };
}

export async function saveWorkInstruction(data: any) {
  const res = await apiClient.post("/work-instruction/save", data);
  return res.data as { success: boolean; data?: any; message?: string };
}

export async function deleteWorkInstructions(ids: string[]) {
  const res = await apiClient.post("/work-instruction/delete", { ids });
  return res.data as { success: boolean; deletedCount?: number; message?: string };
}

export async function getWIItemSource(params?: Record<string, any>) {
  const res = await apiClient.get("/work-instruction/source/item", { params });
  return res.data as PaginatedResponse;
}

export async function getWISalesOrderSource(params?: Record<string, any>) {
  const res = await apiClient.get("/work-instruction/source/sales-order", { params });
  return res.data as PaginatedResponse;
}

export async function getWIProductionPlanSource(params?: Record<string, any>) {
  const res = await apiClient.get("/work-instruction/source/production-plan", { params });
  return res.data as PaginatedResponse;
}

export async function getEquipmentList() {
  const res = await apiClient.get("/work-instruction/equipment");
  return res.data as { success: boolean; data: { id: string; equipment_code: string; equipment_name: string }[] };
}

export async function getEmployeeList() {
  const res = await apiClient.get("/work-instruction/employees");
  return res.data as { success: boolean; data: { user_id: string; user_name: string; dept_name: string | null }[] };
}

// ─── 라우팅 & 공정작업기준 API ───

export interface RoutingProcess {
  routing_detail_id: string;
  seq_no: string;
  process_code: string;
  process_name: string;
  is_required?: string;
  work_type?: string;
}

export interface RoutingVersionData {
  id: string;
  version_name: string;
  description?: string;
  is_default: boolean;
  processes: RoutingProcess[];
}

export interface WIWorkItemDetail {
  id?: string;
  work_item_id?: string;
  detail_type?: string;
  content?: string;
  is_required?: string;
  sort_order?: number;
  remark?: string;

  // 검사항목(inspection) 전용
  process_inspection_apply?: string; // "apply" | "none"
  inspection_code?: string;
  inspection_method?: string;
  unit?: string;
  lower_limit?: string;
  upper_limit?: string;
  base_value?: string;
  tolerance?: string;
  auto_collect?: string; // "Y" | "N"
  plc_data?: string;

  // 작업절차(procedure) 전용
  duration_minutes?: number;

  // 직접입력(input) 전용
  input_type?: string;

  // 문서참조(lookup) 전용
  lookup_target?: string;
  display_fields?: string;

  // 설비점검(equip_inspection) 전용
  equip_inspection_apply?: string; // "apply" | "none"

  // 설비조건(equip_condition) 전용
  condition_name?: string;
  condition_unit?: string;
  condition_base_value?: string;
  condition_tolerance?: string;
  condition_auto_collect?: string;
  condition_plc_data?: string;

  // 실적등록(production_result) 전용
  work_qty_auto_collect?: string;
  work_qty_plc_data?: string;
  defect_qty_auto_collect?: string;
  defect_qty_plc_data?: string;
  good_qty_auto_collect?: string;
  good_qty_plc_data?: string;

  // 자재투입(material_input) 전용 - BOM 자동연동
  material_code?: string;
  material_name?: string;
  quantity?: string;
  material_unit?: string;
  selected_bom_items?: string[] | string;
  bom_item_id?: string;
  bom_item_name?: string;
  bom_qty?: string;
  bom_unit?: string;
}

export interface WIWorkItem {
  id?: string;
  routing_detail_id?: string;
  work_phase: string;
  title: string;
  is_required: string;
  sort_order: number;
  description?: string;
  detail_count?: number;
  details?: WIWorkItemDetail[];
  source_work_item_id?: string;
}

export interface WIWorkStandardProcess {
  routing_detail_id: string;
  seq_no: string;
  process_code: string;
  process_name: string;
  workItems: WIWorkItem[];
}

export async function getRoutingVersions(wiNo: string, itemCode: string) {
  const res = await apiClient.get(`/work-instruction/${wiNo}/routing-versions/${encodeURIComponent(itemCode)}`);
  return res.data as { success: boolean; data: RoutingVersionData[] };
}

export async function updateWIRouting(wiNo: string, routingVersionId: string) {
  const res = await apiClient.put(`/work-instruction/${wiNo}/routing`, { routingVersionId });
  return res.data as { success: boolean };
}

export async function getWIWorkStandard(wiNo: string, routingVersionId: string) {
  const res = await apiClient.get(`/work-instruction/${wiNo}/work-standard`, { params: { routingVersionId } });
  return res.data as { success: boolean; data: { processes: WIWorkStandardProcess[]; isCustom: boolean } };
}

export async function copyWorkStandard(wiNo: string, routingVersionId: string) {
  const res = await apiClient.post(`/work-instruction/${wiNo}/work-standard/copy`, { routingVersionId });
  return res.data as { success: boolean };
}

export async function saveWIWorkStandard(wiNo: string, routingDetailId: string, workItems: WIWorkItem[]) {
  const res = await apiClient.put(`/work-instruction/${wiNo}/work-standard/save`, { routingDetailId, workItems });
  return res.data as { success: boolean };
}

export async function resetWIWorkStandard(wiNo: string) {
  const res = await apiClient.delete(`/work-instruction/${wiNo}/work-standard/reset`);
  return res.data as { success: boolean };
}
