"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 ClientProjectResult {
  id: number;
  customerId: number;
  customerCode: string;
  customerName: string;
  subsidiaryId: number;
  subsidiaryCode: string;
  subsidiaryName: string;
  projectNo: number;
}

export const fetchAllClientProjects = cache(async () => {
  return serverFetchJson<ClientProjectResult[]>(`${BASE_API_URL}/dashboard/searchCustomerSubsidiary`);
});

export const fetchAllClientSubsidiaryProjects = cache(async (customerId: number, tableSorting:string, subsidiaryId?: number) => {
  if (subsidiaryId === 0){
    return serverFetchJson<ClientSubsidiaryProjectResult[]>(
      `${BASE_API_URL}/dashboard/searchCustomerSubsidiaryProject?customerId=${customerId}&subsidiaryId=${subsidiaryId}&tableSorting=${tableSorting}`
    );
  } else if (subsidiaryId === undefined) {
    return serverFetchJson<ClientSubsidiaryProjectResult[]>(
      `${BASE_API_URL}/dashboard/searchCustomerSubsidiaryProject?customerId=${customerId}&tableSorting=${tableSorting}`
    );
  } else {
    return serverFetchJson<ClientSubsidiaryProjectResult[]>(
      `${BASE_API_URL}/dashboard/searchCustomerSubsidiaryProject?customerId=${customerId}&subsidiaryId=${subsidiaryId}&tableSorting=${tableSorting}`
    );
  }
  
});
