"use server"

import { serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { revalidateTag } from "next/cache";
import { cache } from "react";


export interface comboProp {
  id: any;
  label: string;
}

export interface combo {
  records: comboProp[];
}
export interface CreateDepartmentInputs {
    id: number;
    code: string;
    name: string;
    description: string;
}

export const saveDepartment = async (data: CreateDepartmentInputs) => {
    const newDepartment = serverFetchJson(`${BASE_API_URL}/departments/new`, {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    });

    revalidateTag("departments")
    return newDepartment
};

export const deleteDepartment = async (id: number) => {
    const department = await serverFetchWithNoContent(
        `${BASE_API_URL}/departments/${id}`,
        {
            method: "DELETE",
            headers: { "Content-Type": "application/json" },
        },
    );

    revalidateTag("departments")
    return department
};


export const fetchDepartmentCombo = cache(async () => {
  return serverFetchJson<combo>(`${BASE_API_URL}/departments/combo`, {
    next: { tags: ["department"] },
  });
});