"use server";

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

export interface CreateProjectInputs {
  // Project
  projectId: number | null;
  projectDeleted: boolean | null;
  projectCode: string;
  projectName: string;
  projectCategoryId: number;
  projectDescription: string;
  projectLeadId: number;
  projectSubLeadId: number;
  projectActualStart: string;
  projectActualEnd: string;
  projectPlanStart: string;
  projectPlanEnd: string;
  projectStatus: string;
  isClpProject: boolean;
  mainProjectId?: number | null;

  // Project info
  serviceTypeId: number;
  fundingTypeId: number;
  contractTypeId: number;
  locationId: number;
  buildingTypeIds: number[];
  workNatureIds: number[];
  taskTemplateId?: number | "All";

  // Client details
  clientId: Customer["id"];
  clientContactId?: number;
  clientSubsidiaryId?: number | null;
  subsidiaryContactId?: number;
  isSubsidiaryContact?: boolean;
  clientTypeId?: number;

  // Allocation
  totalManhour: number;
  manhourPercentageByGrade: ManhourAllocation;
  taskGroups: {
    [taskGroup: TaskGroup["id"]]: {
      taskIds: Task["id"][];
      percentAllocation: number;
    };
  };
  allocatedStaffIds: number[];
  ratePerManhour: number;

  // Milestones
  milestones: {
    [taskGroupId: TaskGroup["id"]]: {
      startDate: string | null;
      endDate: string | null;
      payments: PaymentInputs[];
    };
  };

  // Miscellaneous
  expectedProjectFee: number;
  subContractFee?: number;
}

export interface ManhourAllocation {
  [gradeId: number]: number;
}

export interface PaymentInputs {
  id: number;
  description: string;
  date: string;
  amount: number;
}

export interface CreateProjectResponse {
  id: number;
  name: string;
  code: string;
  category: string;
  team: string;
  client: string;
  message: string;
  errorPosition: string;
}

export const saveProject = async (data: CreateProjectInputs) => {
  const newProject = await serverFetchJson<CreateProjectResponse>(
    `${BASE_API_URL}/projects/new`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );

  revalidateTag("projects");
  return newProject;
};

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

  revalidateTag("projects");
  revalidatePath("/(main)/home");
  return project;
};

export const importProjects = async (data: FormData) => {
  const importProjects = await serverFetchString<string>(
    `${BASE_API_URL}/projects/import`,
    {
      method: "POST",
      body: data,
    },
  );

  return importProjects;
};
