import React from "react";
import ResourceOvercomsumptionReportLoading from "./ResourceOverconsumptionReportLoading";
import ResourceOverconsumptionReport from "./ResourceOverconsumptionReport";
import { fetchTeam } from "@/app/api/team";
import { fetchAllCustomers } from "@/app/api/customer";
import { fetchAllSubsidiaries } from "@/app/api/subsidiary";
import { getServerSession } from "next-auth";
import { authOptions } from "@/config/authConfig";
import { TEAM_LEAD } from "@/middleware";

interface SubComponents {
  Loading: typeof ResourceOvercomsumptionReportLoading;
}

const ResourceOvercomsumptionReportWrapper: React.FC &
  SubComponents = async () => {
  const session: any = await getServerSession(authOptions);
  const teamId = session.staff?.teamId;
  const role = session.role;
  let needAll = true; 
  let teams = await fetchTeam();
  const [customers, subsidiaries] = await Promise.all([
    fetchAllCustomers(),
    fetchAllSubsidiaries(),
  ]);

  if (role.includes(TEAM_LEAD)) {
    needAll = false;
    teams = teams.filter((team) => team.id === teamId);
  }

  return (
    <ResourceOverconsumptionReport
      team={teams}
      customer={customers}
      subsidiaries={subsidiaries}
      needAll={needAll}
    />
  );
};

ResourceOvercomsumptionReportWrapper.Loading =
  ResourceOvercomsumptionReportLoading;

export default ResourceOvercomsumptionReportWrapper;
