import { eq } from "drizzle-orm";
import { requireUser } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import { AccountShell } from "@/components/account/AccountShell";

export const dynamic = "force-dynamic";

/**
 * Wraps every /account/* page with the members-panel sidebar. Loads the
 * member's identity once so sub-pages don't have to duplicate the query
 * just to render the sidebar.
 */
export default async function AccountLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await requireUser();
  const sessionUser = session.user as {
    id?: string;
    email?: string | null;
    name?: string | null;
    role?: string;
  };

  const [row] = sessionUser.id
    ? await db
        .select({
          name: users.name,
          email: users.email,
          avatarPath: users.avatarPath,
          role: users.role,
        })
        .from(users)
        .where(eq(users.id, sessionUser.id))
        .limit(1)
    : [];

  const memberName = row?.name ?? sessionUser.name ?? "Member";
  const memberEmail = row?.email ?? sessionUser.email ?? "";
  const isAdmin = (row?.role ?? sessionUser.role) === "admin";

  return (
    <AccountShell
      memberName={memberName}
      memberEmail={memberEmail}
      avatarPath={row?.avatarPath ?? null}
      isAdmin={isAdmin}
    >
      {children}
    </AccountShell>
  );
}
