import { cache } from "react";
import "server-only";
// import { serverFetchJson } from "@/app/utils/fetchUtil";
// import { BASE_API_URL } from "@/config/api";
import { serverFetchJson } from "../../utils/fetchUtil";
import { BASE_API_URL } from "../../../config/api";
import { Uom } from "../settings/uom";
import { RecordsRes } from "../utils";
// import { IQCItems } from "@/components/DashboardPage/QC/SupervisorQcApproval";

export interface PoResult {
  id: number;
  code: string;
  orderDate: string;
  supplier: string;
  estimatedArrivalDate: string;
  completedDate: string;
  escalated: boolean;
  status: string;
  pol?: PurchaseOrderLine[];
}

export interface PurchaseOrderLine {
  id: number;
  purchaseOrderId: number;
  itemId: number;
  itemNo: string;
  itemName: string;
  qty: number;
  processed: number;
  uom: Uom;
  price: number;
  status: string;
  stockInLine: StockInLine[];
}

export interface StockInLine {
  id: number;
  stockInId: number;
  purchaseOrderId?: number;
  purchaseOrderLineId: number;
  itemId: number;
  itemNo: string;
  itemName: string;
  itemType: string;
  demandQty: number;
  acceptedQty: number;
  price: number;
  priceUnit: string;
  shelfLife?: number;
  receiptDate?: string;
  productionDate?: string;
  expiryDate?: string;
  status: string;
  supplier: string;
  lotNo: string;
  poCode: string;
  uom: Uom;
  defaultWarehouseId: number; // id for now
}

export const fetchPoList = cache(async (queryParams?: Record<string, any>) => {
  if (queryParams) {
    const queryString = new URLSearchParams(queryParams).toString();
    return serverFetchJson<RecordsRes<PoResult[]>>(
      `${BASE_API_URL}/po/list?${queryString}`,
      {
        method: "GET",
        next: { tags: ["po"] },
      },
    );
  } else {
    return serverFetchJson<RecordsRes<PoResult[]>>(`${BASE_API_URL}/po/list`, {
      method: "GET",
      next: { tags: ["po"] },
    });
  }
});

export const fetchPoWithStockInLines = cache(async (id: number) => {
  return serverFetchJson<PoResult>(`${BASE_API_URL}/po/detail/${id}`, {
    next: { tags: ["po"] },
  });
});

export const fetchIqcLogByUser = cache(async () => {
  // return serverFetchJson<IQCItems[]>(`${BASE_API_URL}/supervisionApprovalLog/stock-in`, {
  //   next: { tags: ["qcLog"] },
  // });
  return undefined;
});
