import { serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { cache } from "react";
import "server-only";
import { NewTaskTemplateFormInputs } from "./actions";
import { Grade } from "../grades";

export interface TaskGroup {
  id: number;
  name: string;
}

export interface Task {
  id: number;
  name: string;
  description: string | null;
  taskGroup: TaskGroup;
}

export interface TaskTemplateGradeAllocation {
  grade: Grade;
  percentage: number;
}

export interface TaskTemplateGroupAllocation {
  taskGroup: TaskGroup;
  percentage: number;
}

export interface TaskTemplate {
  id: number;
  code: string;
  name: string;
  tasks: Task[];
  gradeAllocations: TaskTemplateGradeAllocation[];
  groupAllocations: TaskTemplateGroupAllocation[];
}

export const preloadTaskTemplates = () => {
  fetchTaskTemplates();
};

export const fetchTaskTemplates = cache(async () => {
  return serverFetchJson<TaskTemplate[]>(`${BASE_API_URL}/tasks/templates`, {
    next: { tags: ["taskTemplates"] },
  });
});

export const preloadAllTasks = () => {
  fetchAllTasks();
};

export const fetchAllTasks = cache(async () => {
  return serverFetchJson<Task[]>(`${BASE_API_URL}/tasks`, {
    next: { tags: ["tasks"] },
  });
});

export const fetchTaskTemplateDetail = cache(async (id: string) => {
  const taskTemplate = await serverFetchJson<NewTaskTemplateFormInputs>(
    `${BASE_API_URL}/tasks/templatesDetails/${id}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    },
  );

  return taskTemplate;
});
