import "server-only";
import { Pageable, serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { cache } from "react";
import { String } from "lodash";

interface PickOrderItemInfo {
  name: string;
  type: string;
}

export interface PickOrderResult {
  id: number;
  code: string;
  consoCode?: string;
  targetDate: string;
  completeDate?: number[];
  type: string;
  status: string;
  releasedBy: string;
  items?: PickOrderItemInfo[] | null;
  pickOrderLine?: PickOrderLine[];
}

export interface PickOrderLine {
  id: number;
  itemId: number;
  itemCode: string;
  itemName: string;
  availableQty: number;
  requiredQty: number;
  uomCode: string;
  uomDesc: string;
}
export interface StockOutLine {
  id: number;
  itemId: number;
  itemName: string;
  itemNo: string;
  qty: number;
  stockOutId?: number;
  pickOrderLineId: number;
  lotNo?: string;
  inventoryLotLineId?: number;
  status: string;
  pickTime?: string;
}
export interface ConsoPickOrderResult {
  id: number;
  code: string;
  consoCode?: string;
  targetDate: number[];
  completeDate?: number[];
  type: string;
  status: string;
  releasedBy: string;
  items?: PickOrderItemInfo[] | null;
}

export interface FetchPickOrders extends Pageable {
  code: string | undefined;
  targetDateFrom: string | undefined;
  targetDateTo: string | undefined;
  type: string | undefined;
  status: string | undefined;
  itemName: string | undefined;
}
export type ByItemsSummary = {
  id: number;
  code: string;
  name: string;
  uomDesc: string;
  availableQty: number;
  requiredQty: number;
};
export interface PreReleasePickOrderSummary {
  consoCode: string;
  pickOrders: Omit<PickOrderResult, "items">[];
  items: ByItemsSummary[];
}

export interface PickOrderLineWithSuggestedLot {
  poStatus: string;
  id: number;
  itemName: string;
  qty: number;
  uom: string;
  status: string;
  warehouse: string;
  suggestedLotNo: string;
}

export const PreloadPickOrder = () => {
  fetchPickOrders({
    code: undefined,
    targetDateFrom: undefined,
    targetDateTo: undefined,
    type: undefined,
    status: undefined,
    itemName: undefined,
  });
};

export const fetchPickOrders = cache(async (queryParams: FetchPickOrders) => {
  const queryString = new URLSearchParams(
    queryParams as Record<string, any>,
  ).toString();
  return serverFetchJson<PickOrderResult[]>(
    `${BASE_API_URL}/pickOrder/list?${queryString}`,
    {
      next: {
        tags: ["pickOrders"],
      },
    },
  );
});
