import { redirect } from "next/navigation";

import { auth } from "@/auth";
import { prisma } from "@/lib/db";
import { SideNavProvider } from "@/components/nav/side-nav-provider";
import { SideNav } from "@/components/nav/side-nav";
import { ProjectsProvider } from "@/components/projects/projects-context";
import { ScheduledPanelProvider } from "@/components/scheduled/scheduled-panel-provider";
import { ScheduledPanel } from "@/components/scheduled/scheduled-panel";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const session = await auth();
  // Defense in depth: proxy.ts already redirects unauthenticated requests,
  // but every protected data boundary should check for itself too.
  if (!session?.user) redirect("/login");

  // Just the list for the sidebar/`/projects` page -- each project's own
  // board (categories/groups/todos) is fetched separately by its own page.
  const projects = await prisma.project.findMany({
    where: { ownerId: session.user.id },
    orderBy: { createdAt: "asc" },
    select: { id: true, title: true },
  });

  return (
    <SideNavProvider>
      <ScheduledPanelProvider>
        <ProjectsProvider initialProjects={projects}>
          <div className="flex h-screen overflow-hidden">
            <SideNav userEmail={session.user.email ?? ""} role={session.user.role} />
            <main className="flex-1 overflow-auto">{children}</main>
            <ScheduledPanel />
          </div>
        </ProjectsProvider>
      </ScheduledPanelProvider>
    </SideNavProvider>
  );
}
