import { requireUser, isOrganizer } from "@/lib/auth";
import { db } from "@/lib/db";
import { getOrgContext } from "@/lib/org";
import { ConsoleSidebar } from "@/components/console-sidebar";
import { switchOrgAction, consoleLogoutAction } from "./actions";

/**
 * Organizer Console shell: persistent left sidebar for org-level management.
 * Volunteers and plain conference staff fall through to the simple layout —
 * their pages render without the console chrome.
 */
export default async function ConsoleLayout({ children }: { children: React.ReactNode }) {
  const user = await requireUser();
  const ctx = await getOrgContext();

  const memberships = user.platformRole === "USER"
    ? await db.confMember.findMany({ where: { userId: user.id }, select: { role: true } })
    : [];
  const volunteerOnly =
    user.platformRole === "USER" && memberships.length > 0 && memberships.every((m) => m.role === "VOLUNTEER");

  const showConsole = !volunteerOnly && ctx && (isOrganizer(user) || ctx.orgs.length > 0);

  if (!showConsole) return <>{children}</>;

  const unread = await db.notification.count({ where: { userId: user.id, readAt: null } });

  return (
    <div className="mx-auto flex max-w-[1400px]">
      <ConsoleSidebar
        org={ctx.org ? { id: ctx.org.id, name: ctx.org.name, logoUrl: ctx.org.logoUrl } : null}
        orgs={ctx.orgs}
        user={{ name: user.name, email: user.email, avatarUrl: user.avatarUrl }}
        role={ctx.role}
        modules={ctx.modules}
        unread={unread}
        switchOrg={switchOrgAction}
        logout={consoleLogoutAction}
      />
      <div className="min-w-0 flex-1 px-4 py-6 sm:px-6">{children}</div>
    </div>
  );
}
