"use server"

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


export type CreateNewExpense = {
    expenseNo: string | undefined,
    projectCode: string | undefined,
    issueDate: Date,
    issuedAmount: number,
    receiptDate: Date,
    receivedAmount: number
  }
 
export type PostExpenseData = {
    expenseNo?: string,
    projectId: number,
    projectCode: string,
    amount: number,
    issueDate?: string | null,
    receiptDate?: string,
    remarks?: string
  } 
export const saveProjectExpense = async (data: PostExpenseData[]) => {
  const response = await serverFetchJson(`${BASE_API_URL}/project-expense/create`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("projectExpenses");
  return response;
}

export const updateProjectExpense = async (data: any) => {
  console.log(data)
  const response = await serverFetchJson<any>(`${BASE_API_URL}/project-expense/update`, {
    method: "Post",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  
  revalidateTag("projectExpenses")
  return response;
}

export const deleteProjectExpense = async (rowId: number) => {
  const response = await serverFetchWithNoContent(`${BASE_API_URL}/project-expense/${rowId}`,
    {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
    },
  )

  revalidateTag("projectExpenses");
  return response;
}