import { apiClient } from "./client";

export interface OrderListFilter {
  category_cd?: string;
  search_poNo?: string;
  customer_objid?: string;
  search_partObjId?: string;
  search_serialNo?: string;
  contract_result?: string;
  order_start_date?: string;
  order_end_date?: string;
  due_start_date?: string;
  due_end_date?: string;
  product?: string;
  area_cd?: string;
  paid_type?: string;
  contract_currency?: string;
}

export interface OrderRow {
  objid: string;
  contract_no: string | null;
  category_cd: string | null;
  customer_objid: string | null;
  customer_name: string | null;
  product: string | null;
  area_cd: string | null;
  paid_type: string | null;
  paid_type_name: string | null;
  product_name: string | null;
  area_name: string | null;
  contract_currency: string | null;
  exchange_rate: string | null;
  po_no: string | null;
  order_date: string | null;
  receipt_date: string | null;
  req_del_date: string | null;
  contract_result: string | null;
  order_supply_price_sum: string | null;
  order_vat_sum: string | null;
  order_total_amount_sum: string | null;
  writer: string | null;
  writer_name: string | null;
  pm_user_id: string | null;
  pm_user_name: string | null;
  regdate: string | null;
  order_quantity: number | null;
  cancel_qty_sum: number | null;
  has_order_data: number | null;
  earliest_due_date: string | null;
  other_due_date_count: number | null;
  item_summary: string | null;
  part_no: string | null;
  serial_no: string | null;
  order_appr_status: string | null;          // 한글 라벨 ('결재완료'/'결재중'/'반려'/'작성중'/'')
  amaranth_status: string | null;            // 원본 상태 (호환용)
  order_amaranth_status: string | null;      // 원본 상태 ('complete'/'inProcess'/'reject'/'create'/'')
  cu01_cnt: number | null;
  is_direct_order: string | null;
}

export interface OrderItem {
  objid?: string;
  seq: number;
  part_objid: string;
  part_no: string;
  part_name: string;
  quantity?: number;
  due_date?: string;
  customer_request?: string;
  order_quantity?: string;
  order_unit_price?: string;
  order_supply_price?: string;
  order_vat?: string;
  order_total_amount?: string;
  cancel_qty?: string;
  return_reason?: string;
  product?: string;
  serials?: string[];
}

export interface OrderBody {
  objid?: string;
  contract_no?: string;
  category_cd?: string;
  customer_objid?: string;
  product?: string;
  area_cd?: string;
  paid_type?: string;
  contract_currency?: string;
  exchange_rate?: string;
  receipt_date?: string;
  order_date?: string;           // 발주일 (wace G2 필수)
  req_del_date?: string;
  po_no?: string;
  contract_result?: string;
  approval_required?: string;    // 결재여부 'Y'|'N'
  is_direct_order?: string;      // 'Y' 기본 (G2 직접등록)
  pm_user_id?: string;
  customer_request?: string;
  shipping_method?: string;
  incoterms?: string;
  items: OrderItem[];
}

export const salesOrderMgmtApi = {
  async list(filter: OrderListFilter = {}) {
    const res = await apiClient.get("/sales/order-mgmt/list", { params: filter });
    return (res.data?.data ?? []) as OrderRow[];
  },
  async detail(objid: string) {
    const res = await apiClient.get(`/sales/order-mgmt/${objid}`);
    return res.data?.data;
  },
  async generateNumber(): Promise<string> {
    const res = await apiClient.get("/sales/order-mgmt/generate-number");
    return res.data?.data?.contractNo ?? "";
  },
  async create(body: OrderBody) {
    const res = await apiClient.post("/sales/order-mgmt", body);
    return res.data?.data as { objid: string; contract_no: string };
  },
  async update(objid: string, body: OrderBody) {
    return (await apiClient.put(`/sales/order-mgmt/${objid}`, body)).data;
  },
  async remove(objid: string) {
    return (await apiClient.delete(`/sales/order-mgmt/${objid}`)).data;
  },
  async setStatus(objid: string, contract_result: string) {
    return (await apiClient.patch(`/sales/order-mgmt/${objid}/status`, { contract_result })).data;
  },
  // 라인별 cancel_qty 다중 UPDATE (wace saveOrderCancelQty 이식)
  async saveCancelQty(objid: string, entries: { itemObjId: string; cancelQty: string | number; orderQty: string | number }[]) {
    return (await apiClient.post(`/sales/order-mgmt/${objid}/cancel-qty`, { entries })).data;
  },
  async formView(objid: string): Promise<{ info: any; items: any[] }> {
    const res = await apiClient.get(`/sales/order-mgmt/${objid}/form-view`);
    return res.data?.data ?? { info: null, items: [] };
  },
  // G9 수주복사 (wace btnCopy → copyEstimateAndOrderInfo 1:1)
  async copyOrder(objid: string): Promise<{ newObjid: string; newContractNo: string }> {
    const res = await apiClient.post(`/sales/order-mgmt/${objid}/copy`);
    return res.data?.data;
  },
  // G4/G11 수주 결재상신 — Amaranth SSO URL 발급
  // wace orderMgmtList.btnApproval → ApprovalService.getAmaranthSsoUrl 1:1
  async startApproval(objid: string, body: { approvalTitle?: string; subjectStr?: string } = {})
    : Promise<{ fullUrl: string; approKey: string; status: string }> {
    const res = await apiClient.post(`/sales/order-mgmt/${objid}/amaranth-approval`, body);
    return res.data?.data;
  },
};
