import { Suspense } from "react";
import { OrgChartClient } from "@/components/orgchart/OrgChartClient";
import { todayIso } from "@/lib/format";
import { loadOrgAsOf } from "@/lib/orgchart-data";
import { loadOpenPositions } from "@/lib/positions";
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: divisions }, { data: departments }, { data: teams }, openPositions, { data: reorgScenarios }] =
    await Promise.all([
      loadOrgAsOf(supabase, asOf),
      supabase.from("divisions").select("*").order("name"),
      supabase.from("departments").select("*"),
      supabase.from("teams").select("*"),
      loadOpenPositions(supabase),
      supabase
        .from("reorg_scenarios")
        .select("id, name, effective_date, applied, applied_at")
        .eq("applied", true)
        .order("applied_at", { ascending: false })
        .limit(5),
    ]);

  return (
    <Suspense>
      <OrgChartClient
        employees={org.employees}
        divisions={divisions ?? []}
        departments={departments ?? []}
        teams={teams ?? []}
        openPositions={openPositions}
        reorgScenarios={reorgScenarios ?? []}
        asOf={asOf}
        today={today}
        projectedCount={org.projectedCount}
        historyStartsAt={org.historyStartsAt}
        focusId={focusId}
      />
    </Suspense>
  );
}
