import { redirect } from "next/navigation";
import { DashboardPage } from "@/components/layout/dashboard-page";
import { withDashboardAccess } from "@/components/layout/dashboard-access";
import { loadScopedLocations } from "@/features/locations/location-server";
import { LocationDetail } from "@/features/locations/location-detail";

function first(value: string | string[] | undefined): string | undefined {
  return Array.isArray(value) ? value[0] : value;
}

export default withDashboardAccess("/locations/[id]", async function DashboardRoute(props: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
  params: Promise<{ id: string }>;
}, role) {
  const query = await props.searchParams;
  const { id } = await props.params;
  if (first(query.tab) === "financial") {
    const reportQuery = new URLSearchParams({ location_id: id });
    for (const key of [
      "start_date",
      "end_date",
      "contract_type",
      "chargepoint",
    ]) {
      const value = first(query[key]);
      if (value) reportQuery.set(key, value);
    }
    redirect(`/reports/financial-report?${reportQuery.toString()}`);
  }
  const directory = await loadScopedLocations();
  const location = directory.locations.find((record) => record.id === id);
  return (
    <DashboardPage role={role}>
      <LocationDetail location={location} error={directory.error} />
    </DashboardPage>
  );
});
