"use server";
import { BASE_API_URL } from "@/config/api";
// import { ServerFetchError, serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { revalidateTag } from "next/cache";
import { cache } from "react";
import { serverFetchJson } from "@/app/utils/fetchUtil";
import { QcItemResult } from "../settings/qcItem";
import { RecordsRes } from "../utils";
import { DoResult } from ".";
import { GridRowId, GridRowSelectionModel } from "@mui/x-data-grid";

export interface CreateConsoDoInput {
  ids: GridRowSelectionModel;
}
export interface DoDetail {
  id: number;
  code: string;
  supplierCode: string;
  shopCode: string;
  currencyCode: string;
  orderDate: string;
  estimatedArrivalDate: string;
  completeDate: string;
  status: string;
  deliveryOrderLines: DoDetailLine[];
}

export interface DoDetailLine {
  id: number;
  itemNo: string;
  qty: number;
  price: number;
  status: string;
  itemName?: string;
  uomCode?: string;
}
export interface ReleaseDoRequest {
  id: number;
}

export interface ReleaseDoResponse {
  id: number;
  entity: { status: string }
}
export const releaseDo = cache(async (data: ReleaseDoRequest) => {
  return await serverFetchJson<ReleaseDoResponse>(`${BASE_API_URL}/do/release`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
})
export const preloadDo = () => {
  fetchDoList();
};

export const fetchDoList = cache(async () => {
  return serverFetchJson<DoResult[]>(`${BASE_API_URL}/do/list`, {
    next: { tags: ["doList"] },
  });
});

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