import { Suspense } from "react";
import { OrgChartClient } from "@/components/orgchart/OrgChartClient";
import type { OrgUnitNode } from "@/components/orgchart/types";
import { todayIso } from "@/lib/format";
import { loadOrgAsOf } from "@/lib/orgchart-data";
import { parseIsoDateParam } from "@/lib/reports";
import { createClient } from "@/lib/supabase/server";

type SearchParams = { asOf?: string; focus?: string };

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export default async function OrgChartPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
  const params = await searchParams;
  const today = todayIso();
  const asOf = parseIsoDateParam(params.asOf) ?? today;
  // Only ever used to match against ids already on the page, but validated
  // so a junk value can't reach the client as an arbitrary string.
  const focusId = params.focus && UUID.test(params.focus) ? params.focus : null;

  const supabase = await createClient();

  const [org, { data: units }] = await Promise.all([
    loadOrgAsOf(supabase, asOf),
    supabase.from("org_units").select("id, org_number, name, parent_id, unit_type").order("org_number"),
  ]);

  return (
    <Suspense>
      <OrgChartClient
        employees={org.employees}
        units={(units ?? []) as OrgUnitNode[]}
        vacancies={org.vacancies}
        asOf={asOf}
        today={today}
        projectedCount={org.projectedCount}
        historyStartsAt={org.historyStartsAt}
        focusId={focusId}
      />
    </Suspense>
  );
}
