/**
 * 자재현황 API 클라이언트
 */

import { apiClient } from "./client";

export interface WorkOrder {
  id: number;
  plan_no: string;
  item_code: string;
  item_name: string;
  plan_qty: number;
  completed_qty: number;
  plan_date: string;
  start_date: string | null;
  end_date: string | null;
  status: string;
  work_order_no: string | null;
  company_code: string;
}

export interface MaterialLocation {
  location: string;
  warehouse: string;
  qty: number;
}

export interface MaterialData {
  code: string;
  name: string;
  required: number;
  current: number;
  unit: string;
  locations: MaterialLocation[];
}

export interface WarehouseData {
  warehouse_code: string;
  warehouse_name: string;
  warehouse_type: string | null;
}

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

export async function getWorkOrders(params: {
  dateFrom?: string;
  dateTo?: string;
  itemCode?: string;
  itemName?: string;
}): Promise<ApiResponse<WorkOrder[]>> {
  try {
    const queryParams = new URLSearchParams();
    if (params.dateFrom) queryParams.append("dateFrom", params.dateFrom);
    if (params.dateTo) queryParams.append("dateTo", params.dateTo);
    if (params.itemCode) queryParams.append("itemCode", params.itemCode);
    if (params.itemName) queryParams.append("itemName", params.itemName);

    const qs = queryParams.toString();
    const url = `/material-status/work-orders${qs ? `?${qs}` : ""}`;
    const response = await apiClient.get(url);
    return response.data;
  } catch (error: any) {
    return { success: false, message: error.message };
  }
}

export async function getMaterialStatus(params: {
  planIds: number[];
  warehouseCode?: string;
}): Promise<ApiResponse<MaterialData[]>> {
  try {
    const response = await apiClient.post(
      "/material-status/materials",
      params
    );
    return response.data;
  } catch (error: any) {
    return { success: false, message: error.message };
  }
}

export async function getWarehouses(): Promise<ApiResponse<WarehouseData[]>> {
  try {
    const response = await apiClient.get("/material-status/warehouses");
    return response.data;
  } catch (error: any) {
    return { success: false, message: error.message };
  }
}
