import { getLocationDirectoryPageData } from "@/features/locations/location-server";
import { DashboardPage } from "@/components/layout/dashboard-page";
import { getDashboardRole } from "@/lib/auth/dashboard-role";
import { FinancialDashboard } from "@/features/analytics/financial/dashboard";
import {
  loadFinancialChargepoints,
  loadFinancialInvestors,
  loadFinancialSection,
} from "@/features/analytics/financial/server";
export default async function DashboardRoute({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const query = await searchParams;
  const role = await getDashboardRole(
    Array.isArray(query.role) ? query.role[0] : query.role,
  );
  if (role !== "admin")
    return (
      <DashboardPage role={role}>
        <p className="panel p-6">
          Revenue and investment management requires an administrator account.
        </p>
      </DashboardPage>
    );
  const page = (key: string) => {
    const value = Number(query[key] ?? 1);
    return Number.isSafeInteger(value) && value > 0 && value <= 10000
      ? value
      : 1;
  };
  const [
    revenue,
    investments,
    settlements,
    chargepoints,
    investors,
    locations,
  ] = await Promise.all([
    loadFinancialSection("revenue-shares", page("revenue_page")),
    loadFinancialSection("investor-investments", page("investment_page")),
    loadFinancialSection("payout-settlements", page("settlement_page")),
    loadFinancialChargepoints(),
    loadFinancialInvestors(),
    getLocationDirectoryPageData(role),
  ]);
  return (
    <DashboardPage role={role}>
      <FinancialDashboard
        chargepoints={chargepoints}
        investors={investors}
        locations={{
          options: locations.locations.map((location) => ({
            value: location.id,
            label: location.name,
            name: location.name,
          })),
          error: locations.error,
        }}
        revenue={revenue}
        investments={investments}
        settlements={settlements}
      />
    </DashboardPage>
  );
}
