"use server";

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

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

export interface combo {
    records: comboProp[];
  }

export interface CreateCompanyInputs {
    id?: number;
    companyCode: string;
    companyName: string;
    brNo: string;
    contactName: string;
    phone: string;
    otHourTo: string;
    otHourFrom: string;
    normalHourTo: string;
    normalHourFrom: string;
    currency: string;
    address: string;
    district: string;
    email: string;
}

export interface EditCompanyInputs {
  id?: number;
  companyCode: string;
  name: string;
  brNo: string;
  contactName: string;
  phone: string;
  otHourTo: number[];
  otHourFrom: number[];
  normalHourTo: number[];
  normalHourFrom: number[];
  currency: string;
  address: string;
  district: string;
  email: string;
}

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

  revalidateTag("companys");
  return newCompany
};

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

});

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

  revalidateTag("companys");
  return department
};
