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 { QcCategoryResult } from "../qcCategory";
import { Uom } from "../uom";

// import { TypeInputs, UomInputs, WeightUnitInputs } from "./actions";

export type ItemQc = {
  id: number; // id = qc_check #
  name: string;
  code: string;
  description: string | undefined;
  instruction: string | undefined;
  lowerLimit: number | undefined;
  upperLimit: number | undefined;
  isActive: boolean | undefined;
};

export type ItemsResultResponse = {
  records: ItemsResult[];
  total: number;
};

export type Item = {
  id: number;
  code: string;
  name: string;
  description?: string;
  remarks?: string;
  type?: string;
  shelfLife?: number;
  countryOfOrigin?: string;
  qcCategory?: QcCategoryResult;
  uom: Uom;
}

export type ItemsResult = {
  id: string | number;
  code: string;
  name: string;
  description: string | undefined;
  remarks: string | undefined;
  shelfLife: number | undefined;
  countryOfOrigin: string | undefined;
  maxQty: number | undefined;
  type: string;
  qcChecks: ItemQc[];
  action?: any;
  fgName?: string;
  excludeDate?: string;
  qcCategory?: QcCategoryResult;
  store_id?: string | undefined;
  warehouse?: string | undefined;
  area?: string | undefined;
  slot?: string | undefined;
  LocationCode?: string | undefined;
  locationCode?: string | undefined; // Backend may return lowercase version
  isEgg?: boolean | undefined;
  isFee?: boolean | undefined;
  isBag?: boolean | undefined;
  averageUnitPrice?: number | string;
  latestMarketUnitPrice?: number;
  latestMupUpdatedDate?: string;
  purchaseUnit?: string;
};

export type Result = {
  item: ItemsResult;
  qcChecks: ItemQc[];
  qcType?: string;
};
export const fetchAllItems = cache(async () => {
  return serverFetchJson<ItemsResult[]>(`${BASE_API_URL}/items`, {
    next: { tags: ["items"] },
  });
});

export const fetchItem = cache(async (id: number) => {
  return serverFetchJson<Result>(`${BASE_API_URL}/items/details/${id}`, {
    next: { tags: ["items"] },
  });
});
