"use server";

import { serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { TaskTemplate } from ".";
import { revalidateTag } from "next/cache";
import { ManhourAllocation } from "@/app/api/projects/actions";
import { Task, TaskGroup } from '@/app/api/tasks';

export interface NewTaskTemplateFormInputs {

  // task template
  code: string;
  name: string;
  taskIds: number[];

  id: number | null;

  // resource allocation template
  manhourPercentageByGrade: ManhourAllocation;
  taskGroups: {
    [taskGroup: TaskGroup["id"]]: {
      taskIds: Task["id"][];
      percentAllocation: number;
    };
  };
}

export interface NewTaskTemplateResponse {
  taskTemplate: TaskTemplate;
  message: string;
}

export const saveTaskTemplate = async (data: NewTaskTemplateFormInputs) => {
  const newTaskTemplate = await serverFetchJson<NewTaskTemplateResponse>(
    `${BASE_API_URL}/tasks/templates/save`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );

  revalidateTag("taskTemplates");

  return newTaskTemplate;
};

export const fetchTaskTemplate = async (id: number) => {
  const taskTemplate = await serverFetchJson<TaskTemplate>(
    `${BASE_API_URL}/tasks/templates/${id}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    },
  );

  return taskTemplate;
};

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

  return taskTemplate
};
