"server=only";

import { serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { cache } from "react";
import { Item } from "../settings/item";
import { Uom } from "../settings/uom";

export type JoStatus = "planning" | "pending" | "processing" | "packaging" | "storing" | "completed"
export type JoBomMaterialStatus = "pending" | "completed"

export interface Operator {
  id: number;
  name: string;
  username: string;
}

export interface JobOrder {
  id: number;
  code: string;
  reqQty: number;
  item: Item;
  itemName: string;
  bomId: number;
  // uom: Uom;
  pickLines?: JoDetailPickLine[];
  status: JoStatus;
  planStart?: number[];
  planStartTo?: string;
  planEnd?: number[];
  type: string;
  jobTypeId: number;
  jobTypeName: string;
  sufficientCount: number;
  insufficientCount: number;
  productionPriority: number;
  // TODO pack below into StockInLineInfo
  stockInLineId?: number;
  stockInLineStatus?: string;
  silHandlerId?: number;
  lotNo?: string;
}

export interface Machine {
  id: number;
  name: string;
  code: string;
  qrCode: string;
}

export interface JoDetail {
  id: number;
  code: string;
  itemCode: string;
  itemName?: string;
  name: string;
  reqQty: number;
  // itemId: number;
  uom: string;
  pickLines: JoDetailPickLine[];
  status: JoStatus;
  planStart: number[];
  planEnd: number[];
  type: string;
  // item?: Item;
}

export interface JoDetailPickLine {
  id: number;
  code: string;
  name: string;
  type: string;
  pickedLotNo?: JoDetailPickedLotNo[];
  reqQty: number;
  uom: string;
  status: JoBomMaterialStatus;
  shortUom: string;
}

export interface JoDetailPickedLotNo {
  lotNo: string;
  qty: number;
  isScanned: boolean;
}

export const fetchJoDetail = cache(async (id: number) => {
  return serverFetchJson<JobOrder>(`${BASE_API_URL}/jo/detail/${id}`,
  {
    method: "GET",
    headers: { "Content-Type": "application/json"},
    next: {
      tags: ["jo"]
    }
  })
})