import { redirect } from "next/navigation";
import { getAuthContext } from "@/lib/auth/auth";
import { db } from "@/lib/db";
import { Sidebar } from "@/components/layout/Sidebar";
import { Topbar } from "@/components/layout/Topbar";

export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
  const auth = await getAuthContext();
  if (!auth) redirect("/login");

  const firstMembership = await db.organizationUser.findFirst({
    where: { userId: auth.user.id, status: "ACTIVE" },
    include: { organization: true },
    orderBy: { invitedAt: "asc" },
  });

  return (
    <div className="flex h-screen">
      <Sidebar />
      <div className="flex flex-1 flex-col">
        <Topbar userName={auth.user.fullName} orgName={firstMembership?.organization.name} />
        <main className="flex-1 overflow-y-auto bg-canvas p-6">{children}</main>
      </div>
    </div>
  );
}
