import type { Metadata } from "next";
import { sql, eq } from "drizzle-orm";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { applications } from "@/lib/db/schema";
import { AdminShell } from "@/components/admin";

export const metadata: Metadata = {
  title: { template: "%s · Admin · OrthoGlobe", default: "Admin · OrthoGlobe" },
  robots: { index: false, follow: false },
};

export const dynamic = "force-dynamic";

export default async function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await requireAdmin();

  const [pendingRow] = await db
    .select({ count: sql<number>`count(*)::int` })
    .from(applications)
    .where(eq(applications.status, "pending"));
  const pendingCount = Number(pendingRow?.count ?? 0);

  const adminName =
    (session.user as { name?: string | null } | undefined)?.name ?? null;

  return (
    <AdminShell adminName={adminName} pendingCount={pendingCount}>
      {children}
    </AdminShell>
  );
}
