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 resolveDbSchema = (): string => {
  const raw = process.env.DATABASE_URL || '';
  try {
    const u = new URL(raw);
    // Prisma-style: ?schema=kord_live
    return u.searchParams.get('schema') || 'public';
  } catch {
    return 'public';
  }
};

const dbSchema = resolveDbSchema();
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  // pg(Pool) doesn't understand Prisma's `?schema=...` param.
  // Force PostgreSQL search_path so both Prisma adapter and raw queries
  // operate on the intended schema (e.g. kord_live).
  options: `-c search_path=${dbSchema}`,
});
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();
    const { rows } = await client.query('SHOW search_path;');
    client.release();
    logger.info(`Connected to PostgreSQL successfully via Driver Adapter. (search_path=${rows?.[0]?.search_path ?? 'unknown'})`);
  } catch (error) {
    logger.error('Failed to connect to PostgreSQL:', error);
    process.exit(1);
  }
};
