import { redirect } from "next/navigation";
import { db } from "@/db";
import { bankAccounts, users } from "@/db/schema";
import { eq } from "drizzle-orm";
import { requireUser } from "@/lib/session";
import { Sidebar } from "@/components/sidebar";
import { Topbar } from "@/components/topbar";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const user = await requireUser();
  const [u] = await db.select().from(users).where(eq(users.id, user.id));
  if (!u?.householdId) redirect("/onboarding");

  const accts = await db
    .select({ id: bankAccounts.id })
    .from(bankAccounts)
    .where(eq(bankAccounts.householdId, u.householdId));

  if (accts.length === 0) redirect("/onboarding");

  return (
    <div className="min-h-screen flex">
      <Sidebar />
      <div className="flex-1 flex flex-col min-w-0">
        <Topbar name={user.name ?? user.email} />
        <div className="flex-1 px-4 sm:px-8 py-6">{children}</div>
      </div>
    </div>
  );
}
