import { redirect } from "next/navigation";

import { PendingAssignment } from "@/modules/auth/components/PendingAssignment";
import { getBootstrapState, getCurrentAuthContext } from "@/modules/core/server/auth";
import { AppShell } from "@/modules/shared/components/AppShell";

export const dynamic = "force-dynamic";

type AppLayoutProps = {
  children: React.ReactNode;
};

export default async function AppLayout({ children }: AppLayoutProps): Promise<React.ReactElement> {
  const bootstrap = await getBootstrapState();
  if (bootstrap.setupRequired) {
    redirect("/setup");
  }

  const context = await getCurrentAuthContext();
  if (!context) {
    redirect("/login");
  }

  if (!context.organization && context.permissions.length === 0) {
    return <PendingAssignment account={context.account} />;
  }

  return (
    <AppShell
      account={context.account}
      organization={context.organization}
      organizations={context.organizations}
      permissions={context.permissions}
    >
      {children}
    </AppShell>
  );
}
