"use server";

import { cache } from 'react';
import { Pageable, serverFetchJson } from "@/app/utils/fetchUtil";
import { Machine, Operator } from ".";
import { BASE_API_URL } from "@/config/api";
import { revalidateTag } from "next/cache";
import { convertObjToURLSearchParams } from "@/app/utils/commonUtil";

export interface SaveJo {
  bomId: number;
  planStart: string;
  planEnd: string;
  reqQty: number;
  type: string;
}

export interface SaveJoResponse {
  id: number;
}

export interface SearchJoResultRequest extends Pageable {
  code: string;
  name: string;
}

export interface SearchJoResultResponse {
  records: SearchJoResult[];
  total: number;
}

export interface SearchJoResult {
  id: number;
  code: string;
  name: string;
  reqQty: number;
  uom: string;
  status: string;
}

export interface ReleaseJoRequest {
  id: number;
}

export interface ReleaseJoResponse {
  id: number;
  entity: { status: string }
}

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[];
  status: string;
}

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)
  const response = serverFetchJson<SearchJoResultResponse>(
    `${BASE_API_URL}/jo/getRecordByPage?${queryStr}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      next: {
        tags: ["jos"]
      }
    }
  )

  return response
})

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

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