"use server";

import { serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { revalidatePath, revalidateTag } from "next/cache";
import { QcCategoryResult } from ".";

export interface CreateQcCategoryInputs {
  code: string;
  name: string;
}

export const saveQcCategory = async (data: SaveQcCategoryInputs) => {
  return serverFetchJson<SaveQcCategoryResponse>(`${BASE_API_URL}/qcCategories/save`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};

export interface SaveQcItemsMapping {
  id: number;
  order: number;
}

export interface SaveQcCategoryInputs {
  id?: number;
  code: string;
  name: string;
  description?: string;
  qcItems: SaveQcItemsMapping[];
}

export interface SaveQcCategoryResponse {
  id?: number;
  code: string;
  name: string;
  description?: string;
  errors: Record<keyof SaveQcCategoryInputs, string>;
  // qcItems: SaveQcItemsMapping[];
}

export const deleteQcCategory = async (id: number) => {
  const response = await serverFetchJson<QcCategoryResult[]>(
    `${BASE_API_URL}/qcCategories/${id}`,
    {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
    },
  );

  revalidateTag("qcCategories");
  revalidatePath("/(main)/settings/qcCategory");

  return response;
};
