"use server";

import { serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { Dayjs } from "dayjs";
import { cache } from "react";    


export interface ClientSubsidiaryProjectResult {
  color: string;
  projectId: number;
  projectCode: string;
  projectName: string;
  team: string;
  teamLead: string;
  expectedStage: string;
  budgetedManhour: number;
  spentManhour: number;
  remainedManhour: number;
  manhourConsumptionPercentage: number;
  comingPaymentMilestone: string;
}

export interface TeamConsumptionResult {
  color: string;
  team: string;
  teamLead: string;
  budgetedManhour: number;
  spentManhour: number;
  remainedManhour: number;
  manhourConsumptionPercentage: number;
}

export interface TeamProjectResult {
  id: number;
  teamId: number;
  teamLeadId: number;
  teamCode: string;
  teamName: string;
  projectNo: number;
}

export const fetchTeamProjects = cache(async () => {
  return serverFetchJson<TeamProjectResult[]>(`${BASE_API_URL}/dashboard/searchTeamProjectNo`);
});

export const fetchAllTeamProjects = cache(async (teamLeadId: number, tableSorting:string) => {
    return serverFetchJson<ClientSubsidiaryProjectResult[]>(
      `${BASE_API_URL}/dashboard/searchTeamProject?teamLeadId=${teamLeadId}&tableSorting=${tableSorting}`
    );

});

export const fetchAllTeamConsumption = cache(async (teamIdList: number[],tableSorting:string) => {
  if (teamIdList.length !== 0) {
    const queryParams = new URLSearchParams();
    queryParams.append('teamIdList', teamIdList.join(','));
    return serverFetchJson<ClientSubsidiaryProjectResult[]>(`${BASE_API_URL}/dashboard/searchTeamConsumption?${queryParams.toString()}&tableSorting=${tableSorting}`);
  } else {
    return [];
  }
  
});

export const fetchAllTeamConsumptionColorOrder = cache(async (teamIdList: number[],tableSorting:string) => {
  if (teamIdList.length !== 0) {
    const queryParams = new URLSearchParams();
    queryParams.append('teamIdList', teamIdList.join(','));
    return serverFetchJson<ClientSubsidiaryProjectResult[]>(`${BASE_API_URL}/dashboard/searchTeamConsumptionColorOrder?${queryParams.toString()}&tableSorting=${tableSorting}`);
  } else {
    return [];
  }
  
});
