import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { Nav } from "@/components/layout/nav";
import { auth } from "@/lib/auth/server";
import { db, users, eq } from "@epicure/db";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const session = await auth.api.getSession({ headers: await headers() });
  if (session) {
    const dbUser = await db.query.users.findFirst({
      where: eq(users.id, session.user.id),
      columns: { onboardingCompletedAt: true },
    });
    if (!dbUser?.onboardingCompletedAt) redirect("/onboarding");
  }

  return (
    <>
      <Nav />
      <main className="flex-1 container mx-auto px-4 py-8">{children}</main>
    </>
  );
}
