import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth/session";
import { getPermissionSet } from "@/lib/auth/permissions";
import { createClient } from "@/lib/supabase/server";
import { Sidebar } from "@/components/layout/sidebar";
import { MobileNav } from "@/components/layout/mobile-nav";
import { Topbar } from "@/components/layout/topbar";
import type { Branch } from "@/lib/types";

export default async function AppLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await requireUser();

  // B2B partners and students get their dedicated restricted portals.
  if (user.role?.slug === "b2b-partner") redirect("/partner");
  if (user.role?.slug === "student") redirect("/portal");
  const permSet = await getPermissionSet();

  const supabase = await createClient();
  const { data: branches } = await supabase
    .from("branches")
    .select("*")
    .eq("is_active", true)
    .order("is_head_office", { ascending: false })
    .order("name");

  return (
    <div className="fixed inset-0 flex overflow-hidden bg-background">
      <Sidebar allowed={[...permSet]} />
      <div className="flex flex-1 flex-col overflow-hidden">
        <Topbar
          fullName={user.full_name}
          email={user.email}
          roleName={user.role?.name ?? "—"}
          branches={(branches as Branch[]) ?? []}
          activeBranchId={user.primary_branch_id}
          mobileNav={<MobileNav allowed={[...permSet]} />}
        />
        <main className="flex-1 overflow-y-auto bg-background p-4 sm:p-6">
          {children}
        </main>
      </div>
    </div>
  );
}
