"use server";

import { cache } from "react";
import { serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { revalidateTag } from "next/cache";
import { convertObjToURLSearchParams } from "@/app/utils/commonUtil";
import type {
  AssignJobOrderResponse,
  CommonActionJoResponse,
  SearchJoResultRequest,
  SearchJoResultResponse,
} from "@/app/api/jo/actions";

/** Workbench-only release body (no flags — endpoint defines behavior). */
export interface WorkbenchReleaseJoRequest {
  id: number;
}

/** Job Order Workbench search — separate URL from `/jo/getRecordByPage`. */
export const fetchJosForWorkbench = cache(async (data?: SearchJoResultRequest) => {
  const queryStr = convertObjToURLSearchParams(data);
  return serverFetchJson<SearchJoResultResponse>(
    `${BASE_API_URL}/jo/workbench/getRecordByPage?${queryStr}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      next: {
        tags: ["jos-workbench"],
      },
    },
  );
});

/** Job Order Workbench release — defers stock out / SPL / SOL to first assign. */
export const releaseJoForWorkbench = cache(async (data: WorkbenchReleaseJoRequest) => {
  const response = await serverFetchJson<CommonActionJoResponse>(`${BASE_API_URL}/jo/workbench/release`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("jo");
  revalidateTag("jos-workbench");
  revalidateTag("jos");
  return response;
});

/** Workbench assign — primes SPL/SOL when release was deferred; use only from Jo Workbench UI. */
export const assignJobOrderPickOrderForWorkbench = async (pickOrderId: number, userId: number) => {
  return serverFetchJson<AssignJobOrderResponse>(
    `${BASE_API_URL}/jo/workbench/assign-job-order-pick-order/${pickOrderId}/${userId}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
    },
  );
};
