"use server";

import { serverFetchJson } from "@/app/utils/fetchUtil";
import { ProjectResult } from "../projects";
import { Task, TaskGroup } from "../tasks";
import { BASE_API_URL } from "@/config/api";
import { revalidatePath, revalidateTag } from "next/cache";

export interface TimeEntry {
  id: number;
  projectId?: ProjectResult["id"];
  taskGroupId?: TaskGroup["id"];
  taskId?: Task["id"];
  inputHours?: number;
  otHours?: number;
  remark?: string;
}

export interface RecordTimesheetInput {
  [date: string]: TimeEntry[];
}

export interface LeaveEntry {
  id: number;
  inputHours: number;
  leaveTypeId: number;
  remark?: string;
}

export interface RecordLeaveInput {
  [date: string]: LeaveEntry[];
}

export const saveTimesheet = async (
  data: RecordTimesheetInput,
  username: string,
) => {
  const savedRecords = await serverFetchJson<RecordTimesheetInput>(
    `${BASE_API_URL}/timesheets/save`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );

  revalidateTag(`timesheets_${username}`);

  return savedRecords;
};

export const saveLeave = async (data: RecordLeaveInput, username: string) => {
  const savedRecords = await serverFetchJson<RecordLeaveInput>(
    `${BASE_API_URL}/timesheets/saveLeave`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );

  revalidateTag(`leaves_${username}`);

  return savedRecords;
};

export const saveMemberEntry = async (data: {
  staffId: number;
  entry: TimeEntry;
  recordDate?: string;
}) => {
  return serverFetchJson<RecordTimesheetInput>(
    `${BASE_API_URL}/timesheets/saveMemberEntry`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
};

export const revalidateCacheAfterAmendment = () => {
  revalidatePath("/(main)/home");
};
