import { PrismaClient } from '@prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
import pg from 'pg'

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

// 1. Create a pool or connection using the underlying driver
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })

// 2. Wrap it in the Prisma adapter
const adapter = new PrismaPg(pool)

// 3. Pass the adapter to the PrismaClient constructor
export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    adapter,
    log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
  })

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