/**
 * 공정정보관리 API 클라이언트
 */

import { apiClient } from "./client";

// ═══ Types ═══

export interface ProcessMaster {
  id: string;
  company_code: string;
  process_code: string;
  process_name: string;
  process_type: string;
  standard_time: string;
  worker_count: string;
  use_yn: string;
}

export interface ProcessEquipment {
  id: string;
  process_code: string;
  equipment_code: string;
  equipment_name?: string;
}

export interface Equipment {
  id: string;
  equipment_code: string;
  equipment_name: string;
}

export interface ItemForRouting {
  id: string;
  item_number: string;
  item_name: string;
  size: string;
  unit: string;
  type: string;
}

export interface RoutingVersion {
  id: string;
  item_code: string;
  version_name: string;
  description: string;
  is_default: boolean;
}

export interface RoutingDetail {
  id: string;
  routing_version_id: string;
  seq_no: string;
  process_code: string;
  process_name?: string;
  is_required: string;
  is_fixed_order: string;
  work_type: string;
  standard_time: string;
  outsource_supplier: string;
}

interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
}

const BASE = "/process-info";

// ═══ 공정 마스터 ═══

export async function getProcessList(params?: {
  processCode?: string;
  processName?: string;
  processType?: string;
  useYn?: string;
}): Promise<ApiResponse<ProcessMaster[]>> {
  try {
    const qp = new URLSearchParams();
    if (params?.processCode) qp.append("processCode", params.processCode);
    if (params?.processName) qp.append("processName", params.processName);
    if (params?.processType) qp.append("processType", params.processType);
    if (params?.useYn) qp.append("useYn", params.useYn);
    const qs = qp.toString();
    const res = await apiClient.get(`${BASE}/processes${qs ? `?${qs}` : ""}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function createProcess(data: Partial<ProcessMaster>): Promise<ApiResponse<ProcessMaster>> {
  try {
    const res = await apiClient.post(`${BASE}/processes`, data);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.response?.data?.message || e.message };
  }
}

export async function updateProcess(id: string, data: Partial<ProcessMaster>): Promise<ApiResponse<ProcessMaster>> {
  try {
    const res = await apiClient.put(`${BASE}/processes/${id}`, data);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.response?.data?.message || e.message };
  }
}

export async function deleteProcesses(ids: string[]): Promise<ApiResponse<{ deletedCount: number }>> {
  try {
    const res = await apiClient.post(`${BASE}/processes/delete`, { ids });
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

// ═══ 공정별 설비 ═══

export async function getProcessEquipments(processCode: string): Promise<ApiResponse<ProcessEquipment[]>> {
  try {
    const res = await apiClient.get(`${BASE}/processes/${processCode}/equipments`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function addProcessEquipment(data: { process_code: string; equipment_code: string }): Promise<ApiResponse<ProcessEquipment>> {
  try {
    const res = await apiClient.post(`${BASE}/process-equipments`, data);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.response?.data?.message || e.message };
  }
}

export async function removeProcessEquipment(id: string): Promise<ApiResponse<void>> {
  try {
    const res = await apiClient.delete(`${BASE}/process-equipments/${id}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function getEquipmentList(): Promise<ApiResponse<Equipment[]>> {
  try {
    const res = await apiClient.get(`${BASE}/equipments`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

// ═══ 등록 품목 관리 (item_routing_registered) ═══

export const ROUTING_SCREEN_CODE = "screen_1599";

export interface RegisteredItem {
  registered_id: string;
  sort_order: string;
  id: string;
  item_name: string;
  item_code: string;
  routing_count: string;
}

const PWS_BASE = "/process-work-standard";

export async function getRegisteredItems(search?: string): Promise<ApiResponse<RegisteredItem[]>> {
  try {
    const qs = new URLSearchParams({
      tableName: "item_info",
      nameColumn: "item_name",
      codeColumn: "item_number",
      routingTable: "item_routing_version",
      routingFkColumn: "item_code",
    });
    if (search) qs.set("search", search);
    const res = await apiClient.get(`${PWS_BASE}/registered-items/${ROUTING_SCREEN_CODE}?${qs.toString()}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function registerItemsBatch(
  items: Array<{ itemId: string; itemCode: string }>
): Promise<ApiResponse<any[]>> {
  try {
    const res = await apiClient.post(`${PWS_BASE}/registered-items/batch`, {
      screenCode: ROUTING_SCREEN_CODE,
      items,
    });
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.response?.data?.message || e.message };
  }
}

export async function unregisterItem(registeredId: string): Promise<ApiResponse<void>> {
  try {
    const res = await apiClient.delete(`${PWS_BASE}/registered-items/${registeredId}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

// ═══ 품목별 라우팅 ═══

export async function searchAllItems(search?: string): Promise<ApiResponse<ItemForRouting[]>> {
  try {
    const qs = search ? `?search=${encodeURIComponent(search)}` : "";
    const res = await apiClient.get(`${BASE}/items/search-all${qs}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function getRoutingVersions(itemCode: string): Promise<ApiResponse<RoutingVersion[]>> {
  try {
    const res = await apiClient.get(`${BASE}/routing-versions/${itemCode}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function createRoutingVersion(data: {
  item_code: string;
  version_name: string;
  description?: string;
  is_default?: boolean;
}): Promise<ApiResponse<RoutingVersion>> {
  try {
    const res = await apiClient.post(`${BASE}/routing-versions`, data);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function deleteRoutingVersion(id: string): Promise<ApiResponse<void>> {
  try {
    const res = await apiClient.delete(`${BASE}/routing-versions/${id}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function getRoutingDetails(versionId: string): Promise<ApiResponse<RoutingDetail[]>> {
  try {
    const res = await apiClient.get(`${BASE}/routing-details/${versionId}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

export async function saveRoutingDetails(
  versionId: string,
  details: Partial<RoutingDetail>[]
): Promise<ApiResponse<void>> {
  try {
    const res = await apiClient.put(`${BASE}/routing-details/${versionId}`, { details });
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}

// ═══ BOM 구성 자재 조회 ═══

export interface BomMaterial {
  id: string;
  child_item_id: string;
  quantity: string;
  detail_unit: string | null;
  process_type: string | null;
  child_item_name: string | null;
  child_item_code: string | null;
  child_item_type: string | null;
  item_unit: string | null;
}

export async function getBomMaterials(itemCode: string): Promise<ApiResponse<BomMaterial[]>> {
  try {
    const res = await apiClient.get(`${BASE}/bom-materials/${encodeURIComponent(itemCode)}`);
    return res.data;
  } catch (e: any) {
    return { success: false, message: e.message };
  }
}
