import { PrismaClient } from "@prisma/client";
import { env, logEnvironment } from "@/lib/env";

/**
 * Prisma client singleton.
 *
 * Connection pool configuration
 * ------------------------------
 * Prisma reads pool settings from query params on DATABASE_URL:
 *   DATABASE_URL="postgresql://.../neondb?connection_limit=20&pool_timeout=30"
 *
 * On Vercel + Neon the defaults (connection_limit=5, pool_timeout=10)
 * are too tight for a page that polls multiple endpoints — we observed
 * "Timed out fetching a new connection from the connection pool"
 * when the Site Tag Analytics page's 5s LIVE poll overlapped with
 * the heavier 30s analytics bundle and the dashboard's cron jobs.
 *
 * Recommended values in production:
 *   connection_limit=20   — allows ~3-4 concurrent serverless lambdas
 *                           to each claim the connections they need
 *                           without queueing
 *   pool_timeout=30       — gives slow queries 3x the default headroom
 *                           before giving up on a connection handoff
 *
 * Also strongly recommended: point DATABASE_URL at Neon's PgBouncer
 * pooler endpoint (host contains `-pooler`), not the direct host.
 * The pooler multiplexes 10,000+ client connections over a small
 * pool of Postgres backends, which is a much better fit for a
 * serverless workload than direct connections.
 *
 * These settings live in env vars (Vercel dashboard / .env.local),
 * not in this file — the Prisma Client honours them automatically
 * via the connection string.
 */
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };

export const prisma =
  globalForPrisma.prisma ||
  new PrismaClient({
    log: env.features.debugMode ? ["warn", "error"] : ["error"],
  });

if (!env.isProd) {
  globalForPrisma.prisma = prisma;
  // Log environment info on first load in development
  logEnvironment();
}
