import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined
}

/**
 * Singleton Prisma client.
 *
 * CPanel shared hosting note: DATABASE_URL must include
 * `?connection_limit=10&connect_timeout=10` to avoid exhausting
 * the MySQL connection pool on Phusion Passenger.
 *
 * In development, the client is stored on `globalThis` so that
 * hot-module replacement (Next.js fast refresh) does not create
 * a new pool on every save.
 */
export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    log:
      process.env.PRISMA_LOG_QUERIES === '1'
        ? ['query', 'error', 'warn']
        : process.env.NODE_ENV === 'development'
        ? ['error', 'warn']
        : ['error'],
  })

if (process.env.NODE_ENV !== 'production') {
  globalForPrisma.prisma = prisma
}
