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

// Prisma 7 requires a driver adapter for direct database connections.
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);

export const prisma = new PrismaClient({
  adapter,
  log: ['warn', 'error'],
});

export const connectDB = async () => {
  try {
    // Adapter-based client connects when first used, 
    // but we can test the pool connection here.
    const client = await pool.connect();
    client.release();
    logger.info('Connected to PostgreSQL successfully via Driver Adapter.');
  } catch (error) {
    logger.error('Failed to connect to PostgreSQL:', error);
    process.exit(1);
  }
};
