import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { HireWizardProvider } from "@/components/hire/HireWizardContext";
import { AppShell } from "@/components/shell/AppShell";
import { loadOpenNotes } from "@/lib/notes";
import { loadOpenPositions } from "@/lib/positions";
import { createClient } from "@/lib/supabase/server";

export default async function AppLayout({ children }: { children: ReactNode }) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  if (!user) redirect("/login");

  // Defense in depth: proxy.ts already redirects any non-active-HR session
  // away before this layout ever renders. Re-checking here means a gap in
  // the proxy matcher (or a future route added outside it) still fails
  // closed instead of silently granting access — see docs/security.md.
  const { data: profile } = await supabase.from("profiles").select("full_name, email, role, is_active").eq("id", user.id).maybeSingle();
  if (profile?.role !== "hr" || profile?.is_active !== true) redirect("/login");

  const userLabel = profile.full_name || profile.email || user.email || "";

  const [openPositions, locationsRes, draftsRes, openNotes] = await Promise.all([
    loadOpenPositions(supabase),
    supabase.from("locations").select("id, name, country").order("name"),
    supabase.from("hire_drafts").select("id, step, payload, updated_at").eq("created_by", user.id).order("updated_at", { ascending: false }),
    loadOpenNotes(supabase),
  ]);

  return (
    <HireWizardProvider openPositions={openPositions} locations={locationsRes.data ?? []} drafts={draftsRes.data ?? []}>
      <AppShell userLabel={userLabel} openNotes={openNotes}>
        {children}
      </AppShell>
    </HireWizardProvider>
  );
}
