"use server";
import { ServerFetchError, serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { StaffResult, data } from ".";
import { cache } from "react";
import { Team, staff } from "../team/actions";
import { revalidateTag } from "next/cache";
export interface CreateCustomInputs {
    // Project details
    projectCode: string;
    projectName: string;
  
    // Miscellaneous
    expectedProjectFee: string;
  }

export interface CreateStaffInputs {
    name: string;
    staffId: string;
    companyId: number;
    salaryId: number;
    skillSetId?: number[];
    joinDate?: string;
    currentPositionId: number;
    joinPositionId?: number;
    gradeId?: number;
    teamId?: number
    departmentId?: number;
    phone1: string;
    phone2?: string;
    email: string;
    emergContactName?: string;
    emergContactPhone?: string;
    employType: string;
    departDate?: string;
    departReason?: string;
    remark?: string;
  }
  
  export interface records {
    id: number;
    name: string;
    // team: Team[];
  }

export const saveStaff = async (data: CreateStaffInputs) => {
  // try {
    const newStaffList = await serverFetchJson(`${BASE_API_URL}/staffs/save`, {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    });
    console.log(newStaffList)
    revalidateTag("staffs");
    return newStaffList
    
  // } catch (e: any) {
  //   console.log(e.response)
  //   throw new ServerFetchError(
  //     "Something went wrong fetching data in serverssssss.",
  //     e.response,
  //   );
  // }
  };

  
export const testing = async (data: CreateStaffInputs) => {
  return serverFetchJson(`${BASE_API_URL}/staffs/testing`, {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    });
  };
  
export const deleteStaff = async (id: number) => {
  const newStaffList = await serverFetchWithNoContent(`${BASE_API_URL}/staffs/delete/${id}`, {
    method: "DELETE",
    // body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("staffs");
  return newStaffList
  };

    
export const fetchStaffEdit = cache(async (id: number) => {
  return serverFetchJson<data>(`${BASE_API_URL}/staffs/${id}`, {
    next: { tags: ["staffs"] },
  });
});

// export const preloadStaffEdit = (id: number) => {
// fetchStaffEdit(id);
// };

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

