"use server";
//import { BASE_API_URL } from "@/config/api";
import { BASE_API_URL } from "../../../config/api";
import { revalidateTag } from "next/cache";
import { cache } from "react";
//import { serverFetchJson } from "@/app/utils/fetchUtil";
import { serverFetchJson } from "../../utils/fetchUtil";
import { QcCategory, QcItemWithChecks } from ".";

// DEPRECIATED
export interface QcResult {
  id: number;
  qcItemId: number;
  name: string;
  code: string;
  stockInLineId?: number;
  stockOutLineId?: number;
  failQty: number;
}
export interface SaveQcResultRequest {
  qcItemId: number;
  itemId: number;
  stockInLineId: number | null;
  stockOutLineId: number;
  failQty: number;
  type: string;
  remarks: string;
  qcPassed: boolean;
}

export interface SaveQcResultResponse {
  id: number | null;
  name: string;
  code: string;
  type?: string;
  message: string | null;
  errorPosition: string;
}
export const fetchQcItemCheck = cache(async (itemId?: number) => {
  let url = `${BASE_API_URL}/qcCheck`;
  if (itemId) url += `/${itemId}`;
  return serverFetchJson<QcItemWithChecks[]>(url, {
    next: { tags: ["qc"] },
  });
});

export const fetchQcCategory = cache(async (itemId: number, type: string = "IQC") => {
  const params = new URLSearchParams({
    itemId: itemId.toString(),
    type,
  }).toString();
  return serverFetchJson<QcCategory>(`${BASE_API_URL}/qcCategories/items?${params}`, {
    next: { tags: ["qc"] },
  });
});

export const fetchQcResult = cache(async (id: number) => {
  return serverFetchJson<QcResult[]>(`${BASE_API_URL}/qcResult/${id}`, {
    next: { tags: ["qc"] },
  });
});

export const fetchPickOrderQcResult = cache(async (id: number) => {
  return serverFetchJson<QcResult[]>(
    `${BASE_API_URL}/qcResult/pick-order/${id}`,
    {
      next: { tags: ["qc"] },
    },
  );
});
export const savePickOrderQcResult = async (data: SaveQcResultRequest) => {
  const response = await serverFetchJson<SaveQcResultResponse>(
    `${BASE_API_URL}/qcResult/new`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("qc");
  return response;
};
