"use server";

import { cache } from 'react';
import { Pageable, ServerFetchError, serverFetchBlob, serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { JobOrder, JoStatus, Machine, Operator } from ".";
import { BASE_API_URL } from "@/config/api";
import { revalidateTag } from "next/cache";
import { convertObjToURLSearchParams } from "@/app/utils/commonUtil";
import { FileResponse } from "@/app/api/pdf/actions"; 

export interface SaveJo {
  bomId: number;
  planStart: string;
  planEnd: string;
  reqQty: number;
  type: string;
  //jobType?: string;
  jobTypeId?: number;
  productionPriority?: number;
}

export interface SaveJoResponse {
  id: number;
}

export interface SearchJoResultRequest extends Pageable {
  code: string;
  itemName?: string;
  planStart?: string;
  planStartTo?: string;
  jobTypeName?: string;
  joSearchStatus?: string;
}

export interface productProcessLineQtyRequest {
  productProcessLineId: number;
  outputFromProcessQty: number;
  outputFromProcessUom: string;
  defectQty: number;
  defectUom: string;
  scrapQty: number;
  scrapUom: string;
}
export interface SearchJoResultResponse {
  records: JobOrder[];
  total: number;
}

// DEPRECIATED
export interface SearchJoResult {
  id: number;
  code: string;
  itemCode: string;
  name: string;
  reqQty: number;
  uom: string;
  status: JoStatus;
}

export interface UpdateJoRequest {
  id: number;
  status: string;
}

// For Jo Button Actions
export interface CommonActionJoRequest {
  id: number;
}

export interface CommonActionJoResponse {
  id: number;
  entity: { status: JoStatus }
}

// For Jo Process
export interface IsOperatorExistResponse<T> {
  id: number | null;
  name: string;
  code: string;
  type?: string;
  message: string | null;
  errorPosition: string | keyof T;
  entity: T;
}

export interface isCorrectMachineUsedResponse<T> {
  id: number | null;
  name: string;
  code: string;
  type?: string;
  message: string | null;
  errorPosition: string | keyof T;
  entity: T;
}

export interface JobOrderDetail {
  id: number;
  code: string;
  name: string;
  reqQty: number;
  uom: string;
  pickLines: any[];

  jobTypeName: string;
  status: string;
}

export interface UnassignedJobOrderPickOrder {
  pickOrderId: number;
  pickOrderCode: string;
  pickOrderConsoCode: string;
  pickOrderTargetDate: string;
  pickOrderStatus: string;
  jobOrderId: number;
  jobOrderCode: string;
  jobOrderName: string;
  reqQty: number;
  uom: string;
  planStart: string;
  planEnd: string;
}

export interface AssignJobOrderResponse {
  id: number | null;
  code: string | null;
  name: string | null;
  type: string | null;
  message: string | null;
  errorPosition: string | null;
}

export interface PrintPickRecordRequest{
  pickOrderId: number;
  printerId: number;
  printQty: number;
  floor?: "2F" | "3F" | "4F" | "ALL";
  plasticBoxCartonQty?: number;
  plasticBoxCartonQty2f?: number;
  plasticBoxCartonQty3f?: number;
  plasticBoxCartonQty4f?: number;
}

export interface PrintPickRecordResponse{
  success: boolean;
  message?: string
}

export interface PickRecordPlasticBoxCartonQtyResponse {
  plasticBoxCartonQty2f: number | null;
  plasticBoxCartonQty3f: number | null;
  plasticBoxCartonQty4f: number | null;
}

export const fetchPickRecordPlasticBoxCartonQty = async (
  pickOrderId: number,
): Promise<PickRecordPlasticBoxCartonQtyResponse> => {
  return serverFetchJson<PickRecordPlasticBoxCartonQtyResponse>(
    `${BASE_API_URL}/jo/pick-record-plastic-box-carton-qty/${pickOrderId}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    },
  );
};

export interface PrintFGStockInLabelRequest {
  stockInLineId: number;
  printerId: number;
  printQty?: number;
}

export const printFGStockInLabel = cache(async(data: PrintFGStockInLabelRequest) => {
  const params = new URLSearchParams();
  if (data.stockInLineId) {
    params.append('stockInLineId', data.stockInLineId.toString());
  }
  params.append('printerId', data.printerId.toString());
  if (data.printQty !== undefined && data.printQty !== null) {
    params.append('printQty', data.printQty.toString());
  }
  
  return serverFetchWithNoContent(
    `${BASE_API_URL}/jo/print-FGStockInLabel?${params.toString()}`,
    {
      method: "GET",
      next: {
        tags: ["printFGStockInLabel"],
      },
    }
  );
});
export interface UpdateJoReqQtyRequest {
  id: number;
  reqQty: number;
}

// 添加更新 reqQty 的函数
export const updateJoReqQty = cache(async (data: UpdateJoReqQtyRequest) => {
  return serverFetchJson<SaveJoResponse>(`${BASE_API_URL}/jo/updateReqQty`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  })
})

export const recordSecondScanIssue = cache(async (
  pickOrderId: number,
  itemId: number,
  data: {
    qty: number;  // verified qty (actual pick qty)
    missQty?: number;  //  添加：miss qty
    badItemQty?: number;  //  添加：bad item qty
    isMissing: boolean;
    isBad: boolean;
    reason: string;
    createdBy: number;
    type?: string;  //  type 也应该是可选的
  }
  
) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/second-scan-issue/${pickOrderId}/${itemId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
      next: { tags: ["jo-second-scan"] },
    },
  );
});


export interface ProductProcessResponse {
  id: number;
  productProcessCode: string;
  status: string;
  startTime?: string;
  endTime?: string;
  date: string;
  bomId?: number;
  jobOrderId?: number;
}

export interface ProductProcessLineResponse {
  id: number,
  bomprocessId: number,
  operatorId: number,
  operatorName: string,
  equipmentId: number,
  handlerId: number,
  seqNo: number,
  name: string,
  description: string,
  equipmentDetailId: number,
  equipment_name: string,
  equipmentDetailCode: string,
  status: string,
  byproductId: number,
  byproductName: string,
  byproductQty: number,
  byproductUom: string,
  scrapQty: number,
  defectQty: number,
  defectUom: string,
  outputFromProcessQty: number,
  outputFromProcessUom: string,
  durationInMinutes: number,
  prepTimeInMinutes: number,
  postProdTimeInMinutes: number,
  startTime: string,
  endTime: string,
  isOringinal: boolean,
}

export interface ProductProcessWithLinesResponse {
  id: number;
  productProcessCode: string;
  status: string;
  startTime?: string;
  endTime?: string;
  date: string;
  bomId?: number;
  jobOrderId?: number;
  jobOrderCode: string;
  jobOrderStatus: string;
  bomDescription: string;
  jobType: string;
  isDark: string;
  bomBaseQty: number;
  isDense: number;
  isFloat: string;
  timeSequence: number;
  complexity: number;
  scrapRate: number;
  allergicSubstance: string;
  itemId: number;
  itemCode: string;
  itemName: string;
  outputQty: number;
  outputQtyUom: string;
  productionPriority: number;
  submitedBagRecord?: boolean;
  jobOrderLines: JobOrderLineInfo[];

  productProcessLines: ProductProcessLineResponse[];  
  
}
export interface UpdateProductProcessLineQtyRequest {
  productProcessLineId: number;
  outputFromProcessQty: number;
  outputFromProcessUom: string;
  byproductName: string;
  byproductQty: number;
  byproductUom: string;
  defectQty: number;
  defectUom: string;
  defect2Qty: number;
  defect2Uom: string;
  defect3Qty: number;
  defect3Uom: string;
  defectDescription: string;
  defectDescription2: string;
  defectDescription3: string;
  scrapQty: number;
  scrapUom: string;
}
export interface UpdateProductProcessLineQtyResponse {
  id: number;
  outputFromProcessQty: number;
  outputFromProcessUom: string;
  defectQty: number;
  defectUom: string;
  defect2Qty: number;
  defect2Uom: string;
  defect3Qty: number;
  defect3Uom: string;
  defectDescription: string;
  defectDescription2: string;
  defectDescription3: string;
  scrapQty: number;
  scrapUom: string;
  byproductName: string;
  byproductQty: number;
  byproductUom: string;
}
export interface AllProductProcessResponse {
  id: number;
  productProcessCode: string;
  status: string;
  startTime?: string;
  endTime?: string;
  date: string;
  bomId?: number;
}
export interface AllJoborderProductProcessInfoResponse {
  id: number;
  productProcessCode: string;
  status: string;
  startTime?: string;
  endTime?: string;
  date: string;
  matchStatus: string;
  bomId?: number;
  productionPriority: number;
  assignedTo: number;
  pickOrderId: number;
  pickOrderStatus: string;
  itemCode: string;
  itemName: string;
  bomDescription?: string | null;
  lotNo: string;
  requiredQty: number;
  jobOrderId: number;
  timeNeedToComplete: number;
  uom: string;
  isDrink?: boolean | null;
  stockInLineId: number;
  /** Stock-in-line current status (e.g. receiving/received/partially_completed/completed/rejected). */
  stockInLineStatus?: string | null;
  jobOrderCode: string;
  productProcessLineCount: number;
  FinishedProductProcessLineCount: number;
  lines: ProductProcessInfoResponse[];
}

export interface JobOrderProductProcessPageResponse {
  content: AllJoborderProductProcessInfoResponse[];
  totalJobOrders: number;
  page: number;
  size: number;
}
export interface ProductProcessInfoResponse {
  id: number;
  operatorId?: number;
  operatorName?: string;
  equipmentId?: number;
  equipmentName?: string;
  startTime?: string;
  endTime?: string;
  status: string;
}
export interface ProductProcessLineQrscanUpadteRequest {
  productProcessLineId: number;
  //operatorId?: number;
  //equipmentId?: number;
  equipmentTypeSubTypeEquipmentNo?: string;
  staffNo?: string;
}
export interface NewProductProcessLineQrscanUpadteRequest{
  productProcessLineId: number;
  equipmentCode?: string;
  staffNo?: string;
}

export interface ProductProcessLineDetailResponse {
  id: number,
  productProcessId: number,
  bomProcessId: number,
  operatorId: number,
  equipmentType: string,
  operatorName: string,
  handlerId: number,
  seqNo: number,
  isDark: string,
  isDense: number,
  isFloat: string,
  outputQtyUom: string,
  outputQty: number,
  pickOrderId: number,
  jobOrderCode: string,
  jobOrderId: number,
  name: string,
  description: string,
  equipment: string,
  startTime: string,
  endTime: string,
  defectQty: number,
  defectUom: string,
  scrapQty: number,
  scrapUom: string,
  byproductId: number,
  byproductName: string,
  byproductQty: number,
  byproductUom: string | undefined,
  totalStockQty: number,
  insufficientStockQty: number,
  sufficientStockQty: number,
  productionPriority: number,
  productProcessLines: ProductProcessLineInfoResponse[],
  jobOrderLineInfo: JobOrderLineInfo[],
}
export interface JobOrderProcessLineDetailResponse {
  id: number;
  productProcessId: number;
  bomProcessId: number;
  operatorId: number;
  equipmentType: string | null;
  operatorName: string;
  handlerId: number;
  seqNo: number;
  durationInMinutes: number;
  name: string;
  description: string;
  equipmentId: number;
  startTime: string | number[];  // API 返回的是数组格式
  endTime: string | number[]; 
  stopTime: string | number[]; 
  totalPausedTimeMs?: number; // API 返回的是数组格式
  status: string;
  submitedBagRecord: boolean;
  outputFromProcessQty: number;
  outputFromProcessUom: string;
  defectQty: number;
  defectUom: string;
  defectDescription: string;
  defectQty2: number;
  defectUom2: string;
  defectDescription2: string;
  defectQty3: number;
  defectUom3: string;
  defectDescription3: string;
  scrapQty: number;
  scrapUom: string;
  byproductId: number;
  byproductName: string;
  byproductQty: number;
  byproductUom: string;
  productProcessIssueId: number;
  productProcessIssueStatus: string;
}
export interface JobOrderLineInfo {
  id: number,
  itemId: number,
  itemCode: string,
  itemName: string,
  type: string,

  reqQty: number,
  baseReqQty: number,
  
  stockReqQty: number,

  stockQty: number,
  baseStockQty: number,

  reqUom: string,
  reqBaseUom: string,

  stockUom: string,
  stockBaseUom: string,
  
  availableStatus: string,
  bomProcessId: number,
  bomProcessSeqNo: number,
  isOringinal: boolean

}
export interface ProductProcessLineInfoResponse {
  id: number,
  bomprocessId: number,
  operatorId: number,
  operatorName: string,
  equipmentId: number,
  handlerId: number,
  seqNo: number,
  name: string,
  description: string,
  equipment_name: string,
  equipmentDetailCode: string,
  status: string,
  byproductId: number,
  byproductName: string,
  byproductQty: number,
  byproductUom: string,
  scrapQty: number, 
  defectQty: number, 
  defectUom: string, 
  durationInMinutes: number,
  prepTimeInMinutes: number,
  postProdTimeInMinutes: number,
  outputFromProcessQty: number,
  outputFromProcessUom: string,
  startTime: string,
  endTime: string
}
export interface FloorPickCount {
  floor: string;
  finishedCount: number;
  totalCount: number;
}
export interface AllJoPickOrderResponse {
  id: number;
  pickOrderId: number | null;
  pickOrderCode: string | null;
  jobOrderId: number | null;
  jobOrderCode: string | null;
  jobOrderTypeId: number | null;
  jobOrderType: string | null;
  itemId: number;
  itemName: string;
  bomDescription?: string | null;
  lotNo: string | null;
  planStart?: string | number[] | null;
  reqQty: number;
  uomId: number;
  uomName: string;
  jobOrderStatus: string;
  finishedPickOLineCount: number;
  floorPickCounts: FloorPickCount[];
  noLotPickCount?: FloorPickCount | null;
  suggestedFailCount?: number;
}
export interface UpdateJoPickOrderHandledByRequest {
  pickOrderId: number;
  itemId: number;
  userId: number;
}
export interface JobTypeResponse {
  id: number;
  name: string;
}
export interface SaveProductProcessIssueTimeRequest {
  productProcessLineId: number;
  reason: string;
}
export interface JobOrderLotsHierarchicalResponse {
  pickOrder: PickOrderInfoResponse;
  pickOrderLines: PickOrderLineWithLotsResponse[];
}

/** JO Workbench: same shape as [JobOrderLotsHierarchicalResponse] but `pickOrder.jobOrder` includes BOM code/name. */
export interface JobOrderLotsHierarchicalWorkbenchResponse {
  pickOrder: PickOrderInfoWorkbenchResponse;
  pickOrderLines: PickOrderLineWithLotsResponse[];
}

export interface PickOrderInfoResponse {
  id: number | null;
  code: string | null;
  consoCode: string | null;
  targetDate: string | null;
  type: string | null;
  status: string | null;
  assignTo: number | null;
  jobOrder: JobOrderBasicInfoResponse;
}

export interface PickOrderInfoWorkbenchResponse {
  id: number | null;
  code: string | null;
  consoCode: string | null;
  targetDate: string | null;
  type: string | null;
  status: string | null;
  assignTo: number | null;
  jobOrder: JobOrderBasicInfoWorkbenchResponse;
}

export interface JobOrderBasicInfoResponse {
  id: number;
  code: string;
  name: string;
}

/** BOM header code/name from job order's BOM (workbench hierarchical API only). */
export interface JobOrderBasicInfoWorkbenchResponse {
  id: number;
  code: string;
  name: string;
  itemCode: string | null;
  itemName: string | null;
}

export interface PickOrderLineWithLotsResponse {
  id: number;
  itemId: number | null;
  itemCode: string | null;
  itemName: string | null;
  requiredQty: number | null;
  totalAvailableQty?: number | null;
  uomCode: string | null;
  uomDesc: string | null;
  status: string | null;
  handler: string | null;
  lots: LotDetailResponse[];
  stockouts?: StockOutLineDetailResponse[];
}

export interface StockOutLineDetailResponse {
  id: number | null;
  status: string | null;
  qty: number | null;
  lotId: number | null;
  lotNo: string | null;
  location: string | null;
  availableQty: number | null;
  noLot: boolean;
  /** Workbench API: matched suggest_pick_lot qty for this SOL lot line */
 suggestedPickQty?: number | null;
  suggestedPickLotId?: number | null;
}

export interface LotDetailResponse {
  lotId: number | null;
  lotNo: string | null;
  expiryDate: string | null;
  location: string | null;
  availableQty: number | null;
  requiredQty: number | null;
  actualPickQty: number | null;
  processingStatus: string | null;
  lotAvailability: string | null;
  pickOrderId: number | null;
  pickOrderCode: string | null;
  pickOrderConsoCode: string | null;
  pickOrderLineId: number | null;
  stockOutLineId: number | null;
  stockInLineId: number | null;
  suggestedPickLotId: number | null;
  stockOutLineQty: number | null;
  stockOutLineStatus: string | null;
  routerIndex: number | null;
  routerArea: string | null;
  routerRoute: string | null;
  uomShortDesc: string | null;
  matchStatus?: string | null;
  matchBy?: number | null;
  matchQty?: number | null;
}

export interface JobOrderListForPrintQrCodeResponse {
  id: number;
  code: string;
  name: string;
  reqQty: number;
  stockOutLineId: number;
  stockOutLineQty: number;
  stockOutLineStatus: string;
  finihedTime: string;
}
export interface UpdateJoPlanStartRequest {
  id: number;
  planStart: string; // Format: YYYY-MM-DDTHH:mm:ss or YYYY-MM-DD
}

export const saveProductProcessIssueTime = cache(async (request: SaveProductProcessIssueTimeRequest) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/issue`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(request),
    }
  );
});
export const saveProductProcessResumeTime = cache(async (productProcessIssueId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/resume/${productProcessIssueId}`,
    {
      method: "POST",
    }
  );
});
export const deleteJobOrder=cache(async (jobOrderId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/demo/deleteJobOrder/${jobOrderId}`,
    {
      method: "POST",
    }
  );
});

export const setJobOrderHidden = cache(async (jobOrderId: number, hidden: boolean) => {
  const response = await serverFetchJson<any>(`${BASE_API_URL}/jo/set-hidden`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ id: jobOrderId, hidden }),
  });
  revalidateTag("jos");
  return response;
});
export const fetchAllJobTypes = cache(async () => {
  return serverFetchJson<JobTypeResponse[]>(
    `${BASE_API_URL}/jo/jobTypes`,
    {
      method: "GET",
    }
  );
});
export const updateJoPickOrderHandledBy = cache(async (request: UpdateJoPickOrderHandledByRequest) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/update-jo-pick-order-handled-by`,
    {
      method: "POST",
      body: JSON.stringify(request),
      headers: { "Content-Type": "application/json" },
    },
  );
});
export const fetchJobOrderLotsHierarchicalByPickOrderId = cache(async (pickOrderId: number) => {
  return serverFetchJson<JobOrderLotsHierarchicalResponse>(
    `${BASE_API_URL}/jo/all-lots-hierarchical-by-pick-order/${pickOrderId}`,
    {
      method: "GET",
      next: { tags: ["jo-hierarchical"] },
    },
  );
});

/** JO Workbench: in−out available (matches scan-pick); stockouts include suggestedPickQty / suggestedPickLotId when SPL matches SOL lot line */

export const fetchJobOrderLotsHierarchicalByPickOrderIdWorkbench = cache(
  async (pickOrderId: number) => {
    return serverFetchJson<JobOrderLotsHierarchicalWorkbenchResponse>(
      `${BASE_API_URL}/jo/all-lots-hierarchical-by-pick-order-workbench/${pickOrderId}`,
      {
        method: "GET",
        next: { tags: ["jo-hierarchical-workbench"] },
      },
    );
  },
);

// NOTE: Do NOT wrap in `cache()` because the list needs to reflect just-completed lines
// immediately when navigating back from JobPickExecution.
export interface FetchAllJoPickOrdersFilters {
  jobOrderCode?: string | null;
  pickOrderCode?: string | null;
  itemName?: string | null;
  bomDescription?: string | null;
  planStart?: string | null;
}

export const fetchAllJoPickOrders = async (
  type?: string | null,
  floor?: string | null,
  filters?: FetchAllJoPickOrdersFilters,
) => {
  const params = new URLSearchParams();
  if (type) params.set("type", type);
  if (floor) params.set("floor", floor);
  if (filters?.jobOrderCode) params.set("jobOrderCode", filters.jobOrderCode);
  if (filters?.pickOrderCode) params.set("pickOrderCode", filters.pickOrderCode);
  if (filters?.itemName) params.set("itemName", filters.itemName);
  if (filters?.bomDescription) params.set("bomDescription", filters.bomDescription);
  if (filters?.planStart) params.set("planStart", filters.planStart);
  const query = params.toString() ? `?${params.toString()}` : "";
  return serverFetchJson<AllJoPickOrderResponse[]>(
    `${BASE_API_URL}/jo/AllJoPickOrder${query}`,
    // Force re-fetch. This page reflects real-time pick completion state.
    { method: "GET", cache: "no-store" }
  );
};
export const fetchProductProcessLineDetail = cache(async (lineId: number) => {
  return serverFetchJson<JobOrderProcessLineDetailResponse>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/detail/${lineId}`,
    {
      method: "GET",
    }
  );
});
export const updateProductProcessLineQty = cache(async (request: UpdateProductProcessLineQtyRequest) => {
  return serverFetchJson<UpdateProductProcessLineQtyResponse>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/update/qty/${request.productProcessLineId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(request),
    }
  );
});

export const updateProductProcessLineQrscan = cache(async (request: ProductProcessLineQrscanUpadteRequest) => {
  const requestBody: any = {
    productProcessLineId: request.productProcessLineId,
    //operatorId: request.operatorId,
    //equipmentId: request.equipmentId,
    equipmentTypeSubTypeEquipmentNo: request.equipmentTypeSubTypeEquipmentNo,
    staffNo: request.staffNo,
  };
  if (request.equipmentTypeSubTypeEquipmentNo !== undefined) {
    requestBody["EquipmentType-SubType-EquipmentNo"] = request.equipmentTypeSubTypeEquipmentNo;
  }
  
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/update`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(requestBody),
    }
  );
});


export const newUpdateProductProcessLineQrscan = cache(async (request: NewProductProcessLineQrscanUpadteRequest) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/NewUpdate`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(request),
    }
  );
});
export const fetchAllJoborderProductProcessInfo = cache(async (type?: string | null) => {
  const query = type
    ? `?type=${encodeURIComponent(type)}`
    : "";

  return serverFetchJson<AllJoborderProductProcessInfoResponse[]>(
    `${BASE_API_URL}/product-process/Demo/Process/all${query}`,
    {
      method: "GET",
      next: { tags: ["productProcess"] },
    }
  );
});

export const fetchJoborderProductProcessesPage = cache(async (params: {
  /** Job order planStart 區間起（YYYY-MM-DD，含當日） */
  date?: string | null;
  itemCode?: string | null;
  jobOrderCode?: string | null;
  bomIds?: number[] | null;
  qcReady?: boolean | null;
  type?: string | null;
  includePutaway?: boolean | null;
  /** all | completed | notCompleted */
  putawayStatus?: string | null;
  page?: number;
  size?: number;
}) => {
  const {
    date,
    itemCode,
    jobOrderCode,
    bomIds,
    qcReady,
    includePutaway,
    putawayStatus,
    type,
    page = 0,
    size = 50,
  } = params;

  const queryParts: string[] = [];
  if (date) {
    queryParts.push(`date=${encodeURIComponent(date)}`);
  }
  if (itemCode) queryParts.push(`itemCode=${encodeURIComponent(itemCode)}`);
  if (jobOrderCode) queryParts.push(`jobOrderCode=${encodeURIComponent(jobOrderCode)}`);
  if (bomIds && bomIds.length > 0) queryParts.push(`bomIds=${bomIds.join(",")}`);
  if (qcReady !== undefined && qcReady !== null) queryParts.push(`qcReady=${qcReady}`);
  if (type) queryParts.push(`type=${encodeURIComponent(type)}`);
  if (includePutaway !== undefined && includePutaway !== null) {
    queryParts.push(`includePutaway=${includePutaway}`);
  }
  if (putawayStatus) queryParts.push(`putawayStatus=${encodeURIComponent(putawayStatus)}`);
  queryParts.push(`page=${page}`);
  queryParts.push(`size=${size}`);

  const query = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";

  return serverFetchJson<JobOrderProductProcessPageResponse>(
    `${BASE_API_URL}/product-process/Demo/Process/search${query}`,
    {
      method: "GET",
      next: { tags: ["productProcessSearch"] },
    }
  );
});

/*
export const updateProductProcessLineQty = async (request: UpdateProductProcessLineQtyRequest) => {
  return serverFetchJson<UpdateProductProcessLineQtyResponse>(
    `${BASE_API_URL}/product-process/lines/${request.productProcessLineId}/update/qty`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(request),
    }
  );
};
*/
export const startProductProcessLine = async (lineId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/start/${lineId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    }
  );
};
export const completeProductProcessLine = async (lineId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/complete/${lineId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    }
  );
};

// 查询所有 production processes
export const fetchProductProcesses = cache(async () => {
  return serverFetchJson<{ content: ProductProcessResponse[] }>(
    `${BASE_API_URL}/product-process`,
    {
      method: "GET",
      next: { tags: ["productProcess"] },
    }
  );
});

// 根据 ID 查询
export const fetchProductProcessById = cache(async (id: number) => {
  return serverFetchJson<ProductProcessResponse>(
    `${BASE_API_URL}/product-process/${id}`,
    {
      method: "GET",
      next: { tags: ["productProcess"] },
    }
  );
});
export const updateProductProcessPriority = cache(async (productProcessId: number, productionPriority: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/Process/update/priority/${productProcessId}/${productionPriority}`,
    {
      method: "POST",
    }
  );
});
// 根据 Job Order ID 查询
export const fetchProductProcessesByJobOrderId = cache(async (jobOrderId: number) => {
  return serverFetchJson<ProductProcessWithLinesResponse[]>(
    `${BASE_API_URL}/product-process/demo/joid/${jobOrderId}`,
    {
      method: "GET",
      next: { tags: ["productProcess"] },
    }
  );
});
export const newProductProcessLine = cache(async (lineId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/new/${lineId}`,
    {
      method: "POST",
    }
  );
});
// 获取 process 的所有 lines
export const fetchProductProcessLines = cache(async (processId: number) => {
  return serverFetchJson<ProductProcessLineResponse[]>(
    `${BASE_API_URL}/product-process/${processId}/lines`,
    {
      method: "GET",
      next: { tags: ["productProcessLines"] },
    }
  );
});

// 创建 production process
export const createProductProcess = async (data: {
  bomId: number;
  jobOrderId?: number;
  date?: string;
}) => {
  return serverFetchJson<{ id: number; productProcessCode: string; linesCreated: number }>(
    `${BASE_API_URL}/product-process`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    }
  );
};

// 更新 line 产出数据
export const updateLineOutput = async (lineId: number, data: {
  outputQty?: number;
  outputUom?: string;
  defectQty?: number;
  defectUom?: string;
  scrapQty?: number;
  scrapUom?: string;
  byproductName?: string;
  byproductQty?: number;
  byproductUom?: string;
}) => {
  return serverFetchJson<ProductProcessLineResponse>(
    `${BASE_API_URL}/product-process/lines/${lineId}/output`,
    {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    }
  );
};
export const updateSecondQrScanStatus = cache(async (pickOrderId: number, itemId: number, userId: number, qty: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/update-match-status`,
    {
      method: "POST",
      body: JSON.stringify({
        pickOrderId,
        itemId,
        userId,
        qty
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      next: { tags: ["update-match-status"] },
    },
  );
});

export const submitSecondScanQuantity = cache(async (
  pickOrderId: number, 
  itemId: number, 
  data: { qty: number; isMissing?: boolean; isBad?: boolean; reason?: string; userId?: number }
) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/second-scan-submit/${pickOrderId}/${itemId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
      next: { tags: ["jo-second-scan"] },
    },
  );
});
// 获取未分配的 Job Order pick orders
export const fetchUnassignedJobOrderPickOrders = cache(async () => {
  return serverFetchJson<UnassignedJobOrderPickOrder[]>(
    `${BASE_API_URL}/jo/unassigned-job-order-pick-orders`,
    {
      method: "GET",
      next: { tags: ["jo-unassigned"] },
    },
  );
});

// 分配 Job Order pick order 给用户
export const assignJobOrderPickOrder = async (pickOrderId: number, userId: number) => {
  return serverFetchJson<AssignJobOrderResponse>(
    `${BASE_API_URL}/jo/assign-job-order-pick-order/${pickOrderId}/${userId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    }
  );
};
export const unAssignJobOrderPickOrder = async (pickOrderId: number) => {
  return serverFetchJson<AssignJobOrderResponse>(
    `${BASE_API_URL}/jo/unassign-job-order-pick-order/${pickOrderId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    }
  );
};
// 获取 Job Order 分层数据
export const fetchJobOrderLotsHierarchical = cache(async (userId: number) => {
  return serverFetchJson<JobOrderLotsHierarchicalResponse>(
    `${BASE_API_URL}/jo/all-lots-hierarchical/${userId}`,
    {
      method: "GET",
      next: { tags: ["jo-hierarchical"] },
    },
  );
});
export const fetchCompletedJobOrderPickOrders = cache(async (userId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/completed-job-order-pick-orders/${userId}`,
    {
      method: "GET",
      next: { tags: ["jo-completed"] },
    },
  );
});
/*
// 获取已完成的 Job Order pick orders
export const fetchCompletedJobOrderPickOrdersrecords = cache(async () => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/jo/completed-job-order-pick-orders-only`,
    {
      method: "GET",
      next: { tags: ["jo-completed"] },
    },
  );
});
*/
export interface CompletedJobOrderPickOrderDashboardRecord {
  id?: number;
  pickOrderId?: number;
  pickOrderCode?: string;
  /** YYYY-MM-DD from backend (preferred for grouping) */
  statDate?: string | null;
  completedDate?: string | null;
  planStart?: string | null;
  plasticBoxCartonQty2f?: number | null;
  plasticBoxCartonQty3f?: number | null;
  plasticBoxCartonQty4f?: number | null;
}

export const fetchPlasticBoxCartonQtyDashboard = async (
  from: string,
  to: string,
): Promise<CompletedJobOrderPickOrderDashboardRecord[]> => {
  const params = new URLSearchParams({
    from: from.trim(),
    to: to.trim(),
  });
  return serverFetchJson<CompletedJobOrderPickOrderDashboardRecord[]>(
    `${BASE_API_URL}/jo/plastic-box-carton-qty-dashboard?${params.toString()}`,
    {
      method: "GET",
      cache: "no-store",
    },
  );
};

export const fetchCompletedJobOrderPickOrdersrecords = async (
  completedDate?: string | null,
): Promise<CompletedJobOrderPickOrderDashboardRecord[]> => {
  const q =
    completedDate && String(completedDate).trim() !== ""
      ? `?date=${encodeURIComponent(String(completedDate).trim())}`
      : "";
  return serverFetchJson<CompletedJobOrderPickOrderDashboardRecord[]>(
    `${BASE_API_URL}/jo/completed-job-order-pick-orders-only${q}`,
    {
      method: "GET",
      cache: "no-store",
    },
  );
};
export const fetchJobOrderPickOrdersrecords = async (
  date?: string | null,
  status?: string | null,
) => {
  const params = new URLSearchParams();

  if (date && String(date).trim() !== "") {
    params.set("date", String(date).trim());
  }
  if (status && String(status).trim() !== "" && String(status) !== "All") {
    params.set("status", String(status).trim());
  }

  const q = params.toString() ? `?${params.toString()}` : "";
  return serverFetchJson<any>(`${BASE_API_URL}/jo/job-order-pick-orders${q}`, {
    method: "GET",
    cache: "no-store",
  });
};

export const fetchJobOrderPickOrderLotDetailsForPick = cache(async (pickOrderId: number) => {  
  return serverFetchJson<any[]>(`${BASE_API_URL}/jo/job-order-pick-order-lot-details/${pickOrderId}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" }
  })
})
export const fetchJoForPrintQrCode = cache(async (date: string) => {
  return serverFetchJson<JobOrderListForPrintQrCodeResponse[]>(
    `${BASE_API_URL}/jo/joForPrintQrCode/${date}`,
    {
      method: "GET",
      next: { tags: ["jo-print-qr-code"] },
    },
  );
});
// 获取已完成的 Job Order pick order records
export const fetchCompletedJobOrderPickOrderRecords = cache(async (userId: number) => {
  return serverFetchJson<any[]>(
    `${BASE_API_URL}/jo/completed-job-order-pick-order-records/${userId}`,
    {
      method: "GET",
      next: { tags: ["jo-records"] },
    },
  );
});

export const fetchJobOrderDetailByCode = cache(async (code: string) => {
  return serverFetchJson<JobOrderDetail>(
    `${BASE_API_URL}/jo/detailByCode/${code}`,
    {
      method: "GET",
      next: { tags: ["jo"] },
    },
  );
});
export const isOperatorExist = async (username: string) => {
  const isExist = await serverFetchJson<IsOperatorExistResponse<Operator>>(
    `${BASE_API_URL}/jop/isOperatorExist`,
    {
      method: "POST",
      body: JSON.stringify({ username }),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("po");
  return isExist;
};

export const isCorrectMachineUsed = async (machineCode: string) => {
  const isExist = await serverFetchJson<isCorrectMachineUsedResponse<Machine>>(
    `${BASE_API_URL}/jop/isCorrectMachineUsed`,
    {
      method: "POST",
      body: JSON.stringify({ machineCode }),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("po");
  return isExist;
};


export const fetchJos = cache(async (data?: SearchJoResultRequest) => {
  const queryStr = convertObjToURLSearchParams(data)
  console.log("queryStr", queryStr)
  const fullUrl = `${BASE_API_URL}/jo/getRecordByPage?${queryStr}`;
  console.log("fetchJos full URL:", fullUrl);
  console.log("fetchJos BASE_API_URL:", BASE_API_URL);
  const response = await serverFetchJson<SearchJoResultResponse>(
    `${BASE_API_URL}/jo/getRecordByPage?${queryStr}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      next: {
        tags: ["jos"]
      }
    }
  )
 // console.log("fetchJos response:", response)
  
  return response
})
export interface PostPickOrderResponse<T = null> {
  id: number | null;
  name: string;
  code: string;
  type?: string;
  message: string | null;
  errorPosition: string
  entity?: T | T[];
  consoCode?: string;
}
export interface PickExecutionIssueData {
  type: string;
  pickOrderId: number;
  pickOrderCode: string;
  pickOrderCreateDate: string;
  pickExecutionDate: string;
  pickOrderLineId: number;
  itemId: number;
  itemCode: string;
  itemDescription: string;
  lotId: number|null;
  lotNo: string|null;
  storeLocation: string;
  requiredQty: number;
  actualPickQty: number;
  missQty: number;
  badItemQty: number;
  badPackageQty?: number;
  /** Optional: frontend-only reference to stock_out_line.id for the picked lot. */
  stockOutLineId?: number;
  issueRemark: string;
  pickerName: string;
  handledBy?: number;
  badReason?: string;
  reason?: string;
}
/** 无 miss/bad/bad package：仅后端 hold + SOL checked，不写 pick_execution_issue（避免 DUPLICATE）。 */
export const applyPickExecutionHoldAndChecked = async (data: PickExecutionIssueData) => {
  const result = await serverFetchJson<PostPickOrderResponse>(
    `${BASE_API_URL}/pickExecution/applyHoldAndChecked`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("pickorder");
  return result;
};
export const updateJo = cache(async (data: UpdateJoRequest) => {
  return serverFetchJson<SaveJoResponse>(`${BASE_API_URL}/jo/update`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
})

export const releaseJo = cache(async (data: CommonActionJoRequest) => {
  const response = serverFetchJson<CommonActionJoResponse>(`${BASE_API_URL}/jo/release`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
  
  // Invalidate the cache after releasing
  revalidateTag("jo");
  
  return response;
})

export const startJo = cache(async (data: CommonActionJoRequest) => {
  const response = serverFetchJson<CommonActionJoResponse>(`${BASE_API_URL}/jo/start`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
  
  // Invalidate the cache after starting
  revalidateTag("jo");
  
  return response;
})

export const manualCreateJo = cache(async (data: SaveJo) => {
  return serverFetchJson<SaveJoResponse>(`${BASE_API_URL}/jo/manualCreate`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" }
  })
})

export const fetchCompletedJobOrderPickOrdersWithCompletedSecondScan = cache(async (userId: number) => {
  return serverFetchJson<any[]>(`${BASE_API_URL}/jo/completed-job-order-pick-orders-with-completed-second-scan/${userId}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" }
  })
})
export const fetchCompletedJobOrderPickOrderLotDetails = cache(async (pickOrderId: number) => {
  return serverFetchJson<any[]>(`${BASE_API_URL}/jo/completed-job-order-pick-order-lot-details/${pickOrderId}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" }
  })
})
export const fetchCompletedJobOrderPickOrderLotDetailsForCompletedPick = cache(async (pickOrderId: number) => {  
  return serverFetchJson<any[]>(`${BASE_API_URL}/jo/completed-job-order-pick-order-lot-details-completed-pick/${pickOrderId}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" }
  })
})



export async function PrintPickRecord(request: PrintPickRecordRequest){
  const params = new URLSearchParams();
  params.append('pickOrderId', request.pickOrderId.toString())
  params.append('printerId', request.printerId.toString())
  if (request.printQty !== null && request.printQty !== undefined) {
    params.append('printQty', request.printQty.toString());
  }
  if (request.floor) {
    params.append('floor', request.floor);
  }
  if (request.plasticBoxCartonQty !== null && request.plasticBoxCartonQty !== undefined) {
    params.append('plasticBoxCartonQty', request.plasticBoxCartonQty.toString());
  }
  if (request.plasticBoxCartonQty2f !== null && request.plasticBoxCartonQty2f !== undefined) {
    params.append('plasticBoxCartonQty2f', request.plasticBoxCartonQty2f.toString());
  }
  if (request.plasticBoxCartonQty3f !== null && request.plasticBoxCartonQty3f !== undefined) {
    params.append('plasticBoxCartonQty3f', request.plasticBoxCartonQty3f.toString());
  }
  if (request.plasticBoxCartonQty4f !== null && request.plasticBoxCartonQty4f !== undefined) {
    params.append('plasticBoxCartonQty4f', request.plasticBoxCartonQty4f.toString());
  }

  try {
    await serverFetchWithNoContent(
      `${BASE_API_URL}/jo/print-PickRecord?${params.toString()}`,
      { method: "GET" },
    );
    return {
      success: true,
      message: "Print job sent successfully (Pick Record)",
    } as PrintPickRecordResponse;
  } catch (error) {
    const message =
      error instanceof ServerFetchError
        ? error.message
        : error instanceof Error
          ? error.message
          : "Print failed";
    return { success: false, message } as PrintPickRecordResponse;
  }
}

export interface ExportFGStockInLabelRequest {
  stockInLineId: number;
}

export const fetchFGStockInLabel = async (data: ExportFGStockInLabelRequest): Promise<FileResponse> => {
  const reportBlob = await serverFetchBlob<FileResponse>(
    `${BASE_API_URL}/jo/FGStockInLabel`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );

  return reportBlob;
};
export const updateJoPlanStart = cache(async (data: UpdateJoPlanStartRequest) => {
  return serverFetchJson<SaveJoResponse>(`${BASE_API_URL}/jo/update-jo-plan-start`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
})

export interface UpdateProductProcessLineStatusRequest {
  productProcessLineId: number;
  status: string;
}


export const updateProductProcessLineStatus = async (request: UpdateProductProcessLineStatusRequest) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/update/status`,
    {
      method: "POST",
      body: JSON.stringify(request),
      headers: { "Content-Type": "application/json" },
    }
  );
};
export const passProductProcessLine = async (lineId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/pass/${lineId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    }
  );
};
export interface UpdateProductProcessLineProcessingTimeSetupTimeChangeoverTimeRequest {
  productProcessLineId: number;
  processingTime: number;
  setupTime: number;
  changeoverTime: number;
}
export const updateProductProcessLineProcessingTimeSetupTimeChangeoverTime = async (lineId: number, request: UpdateProductProcessLineProcessingTimeSetupTimeChangeoverTimeRequest) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/update/processingTimeSetupTimeChangeoverTime/${lineId}`,
    {
      method: "POST",
      body: JSON.stringify(request),
      headers: { "Content-Type": "application/json" },
    }
  );
  
};
export interface MaterialPickStatusItem {
  id: number;
  pickOrderId: number | null;
  pickOrderCode: string | null;
  jobOrderId: number | null;
  jobOrderCode: string | null;
  itemId: number | null;
  itemCode: string | null;
  itemName: string | null;
  jobOrderQty: number | null;
  uom: string | null;
  pickStartTime: string | null; // ISO datetime string
  pickEndTime: string | null;    // ISO datetime string
  numberOfItemsToPick: number;
  numberOfItemsWithIssue: number;
  pickStatus: string | null;
}

export const fetchMaterialPickStatus = cache(async (date?: string): Promise<MaterialPickStatusItem[]> => {
  const params = new URLSearchParams();
  if (date) params.set("date", date); // yyyy-MM-dd

  const qs = params.toString();
  const url = `${BASE_API_URL}/jo/material-pick-status${qs ? `?${qs}` : ""}`;
  
  return await serverFetchJson<MaterialPickStatusItem[]>(
    url,
    {
      method: "GET",
    }
  );
})
export interface ProcessStatusInfo {
  processName?: string | null;
  equipmentName?: string | null;
  equipmentDetailName?: string | null;
  /** 經手人姓名（對應 product process line.handler） */
  handlerName?: string | null;
  startTime?: string | null;
  endTime?: string | null;
  isRequired: boolean;
}

export interface JobProcessStatusResponse {
  jobOrderId: number;
  jobOrderCode: string;
  itemCode: string;
  itemName: string;
  status: string;
  processingTime: number | null;
  setupTime: number | null;
  changeoverTime: number | null;
  planEndTime?: string | null;
  processes: ProcessStatusInfo[];
}

export const fetchJobProcessStatus = cache(
  async (date?: string, productProcessStatus?: string | null) => {
    const params = new URLSearchParams();
    if (date) params.set("date", date); // yyyy-MM-dd
    if (productProcessStatus && productProcessStatus.length > 0) {
      params.set("productProcessStatus", productProcessStatus);
    }

    const qs = params.toString();
    const url = `${BASE_API_URL}/product-process/Demo/JobProcessStatus${qs ? `?${qs}` : ""}`;

    return serverFetchJson<JobProcessStatusResponse[]>(url, {
      method: "GET",
      next: { tags: ["jobProcessStatus"] },
    });
  },
);

// ===== Operator KPI Dashboard =====

export interface OperatorKpiProcessInfo {
  jobOrderId?: number | null;
  jobOrderCode?: string | null;
  productProcessId?: number | null;
  productProcessLineId?: number | null;
  processName?: string | null;
  equipmentName?: string | null;
  equipmentDetailName?: string | null;
  startTime?: string | number[] | null;
  endTime?: string | number[] | null;
  processingTime?: number | null;
  itemCode?: string | null;
  itemName?: string | null;
}

export interface OperatorKpiResponse {
  operatorId: number;
  operatorName?: string | null;
  staffNo?: string | null;
  totalProcessingMinutes: number;
  totalJobOrderCount: number;
  currentProcesses: OperatorKpiProcessInfo[];
}

export const fetchOperatorKpi = cache(async (date?: string) => {
  const params = new URLSearchParams();
  if (date) params.set("date", date);
  const qs = params.toString();
  const url = `${BASE_API_URL}/product-process/Demo/OperatorKpi${qs ? `?${qs}` : ""}`;

  return serverFetchJson<OperatorKpiResponse[]>(url, {
    method: "GET",
    next: { tags: ["operatorKpi"] },
  });
});

// ===== Equipment Status Dashboard =====

export interface EquipmentStatusProcessInfo {
  jobOrderId?: number | null;
  jobOrderCode?: string | null;
  productProcessId?: number | null;
  productProcessLineId?: number | null;
  processName?: string | null;
  operatorName?: string | null;
  startTime?: string | number[] | null;
  processingTime?: number | null;
}

export interface EquipmentStatusPerDetail {
  equipmentDetailId: number;
  equipmentDetailCode?: string | null;
  equipmentDetailName?: string | null;
  equipmentId?: number | null;
  equipmentTypeName?: string | null;
  status: string;
  repairAndMaintenanceStatus?: boolean | null;
  latestRepairAndMaintenanceDate?: string | null;
  lastRepairAndMaintenanceDate?: string | null;
  repairAndMaintenanceRemarks?: string | null;
  currentProcess?: EquipmentStatusProcessInfo | null;
}

export interface EquipmentStatusByTypeResponse {
  equipmentTypeId: number;
  equipmentTypeName?: string | null;
  details: EquipmentStatusPerDetail[];
}

export const fetchEquipmentStatus = cache(async () => {
  const url = `${BASE_API_URL}/product-process/Demo/EquipmentStatus`;
  return serverFetchJson<EquipmentStatusByTypeResponse[]>(url, {
    method: "GET",
    next: { tags: ["equipmentStatus"] },
  });
});
export const deleteProductProcessLine = async (lineId: number) => {
  return serverFetchJson<any>(
    `${BASE_API_URL}/product-process/Demo/ProcessLine/delete/${lineId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    }
  );
};
;