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 { PutAwayLine } from "./actions";
import { StockInLine } from "../stockIn";

export enum StockInStatus {
  PENDING = "pending",
  RECEIVED = "received",
  APPROVED = "escalated",
  REJECTED = "rejected",
  COMPLETED = "completed",
}
export interface PoResult {
  id: number;
  code: string;
  orderDate: string;
  supplier: string;
  estimatedArrivalDate: string;
  completedDate: string;
  itemDetail?: string;
  itemCode?: string;
  itemName?: string;
  itemQty?: string;
  itemSumAcceptedQty?: string;
  itemUom?: string;
  escalated: boolean;
  status: string;
  pol?: PurchaseOrderLine[];
}
export type { StockInLine } from "../stockIn";
export interface PurchaseOrderLine {
  id: number;
  purchaseOrderId: number;
  itemId: number;
  itemNo: string;
  itemName: string;
  qty: number;
  processed: number;
  receivedQty: number;
  uom: Uom;
  stockUom: StockUomForPoLine; 
  price: number;
  status: string;
  stockInLine: StockInLine[];
}

export interface StockUomForPoLine {
  id: number;
  stockUomCode: string;
  stockUomDesc: string;
  stockQty: number;
  stockRatioN: number;
  stockRatioD: number;
  purchaseRatioN: number;
  purchaseRatioD: number;
}

// DEPRECIATED
export interface StockInLine_old {
  id: number;
  stockInId?: number;
  purchaseOrderId?: number;
  purchaseOrderLineId: number;
  itemId: number;
  itemNo: string;
  itemName: string;
  itemType: string;
  demandQty: number;
  acceptedQty: number;
  qty?: number;
  processed?: number;
  price?: number;
  priceUnit?: string;
  shelfLife?: number;
  receiptDate?: string;
  productionDate?: string;
  productLotNo?: string;
  expiryDate?: string;
  status: string;
  supplier?: string;
  lotNo?: string;
  poCode?: string;
  uom?: Uom;
  defaultWarehouseId: number; // id for now
  dnNo?: string;
  dnDate?: number[];
  stockQty?: number;
  handlerId?: number;
  putAwayLines?: PutAwayLine[];
}

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"] },
  });
});
