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

// Use the POOLER URL (6543) for the app to handle high traffic
const connectionString = process.env.DATABASE_URL

const createPrismaClient = () => {
    // 1. Create the Pool
    const pool = new Pool({ connectionString })
    // 2. Create the Adapter
    const adapter = new PrismaPg(pool)
    // 3. Init the Client
    return new PrismaClient({ adapter })
}

// Prevent multiple instances during development hot-reloading
declare global {
    var prisma: ReturnType<typeof createPrismaClient> | undefined
}

export const db = globalThis.prisma || createPrismaClient()

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