import { redirect } from "next/navigation";

import { auth } from "@/src/auth";
import SignOutButton from "@/src/components/auth/SignOutButton";
import Navbar from "@/src/components/Navbar";
import { PermissionsProvider } from "@/src/contexts/PermissionsContext";
import { StabilimentoProvider } from "@/src/contexts/StabilimentoContext";
import { getPermissions, normalizeRole } from "@/src/lib/permissions";

export default async function AppShell({ children }: { children: React.ReactNode }) {
  const session = await auth();

  if (!session?.user) {
    redirect("/login");
  }

  const ruolo = normalizeRole(session.user.ruolo);
  if (!ruolo) {
    redirect("/login");
  }

  const permissions = getPermissions(ruolo);

  return (
    <PermissionsProvider ruolo={ruolo} permissions={permissions}>
      <StabilimentoProvider>
        <div>
          <Navbar
            permissions={permissions}
            userLabel={session.user.utente}
            actions={<SignOutButton />}
          />
          <main>{children}</main>
        </div>
      </StabilimentoProvider>
    </PermissionsProvider>
  );
}
