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

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

/**
 * Returns a singleton PrismaClient instance using the Prisma v7 adapter pattern.
 * Uses @prisma/adapter-pg with a pg Pool for direct PostgreSQL connections.
 */
export function getDB(): PrismaClient {
    if (!globalForPrisma.prisma) {
        const connectionString = process.env.DATABASE_URL;
        const pool = new Pool({ connectionString });
        const adapter = new PrismaPg(pool);

        globalForPrisma.prisma = new PrismaClient({ adapter });
    }
    return globalForPrisma.prisma;
}

export default getDB;
