import pg from 'pg';
import dotenv from 'dotenv';

dotenv.config();

const { Pool } = pg;

const {
    DATABASE_URL,
    DB_HOST = 'localhost',
    DB_PORT = '5432',
    DB_USER = 'postgres',
    DB_PASSWORD = 'postgres',
    DB_NAME = 'gohorsejobs',
    DB_SSLMODE = 'disable',
} = process.env;

const config = DATABASE_URL
    ? {
        // Remove sslmode from connection string to avoid conflicts
        connectionString: DATABASE_URL.replace('?sslmode=require', '').replace('&sslmode=require', ''),
        ssl: { rejectUnauthorized: false }
    }
    : {
        host: DB_HOST,
        port: Number(DB_PORT),
        user: DB_USER,
        password: DB_PASSWORD,
        database: DB_NAME,
        ssl: DB_SSLMODE === 'require' ? { rejectUnauthorized: false } : false,
    };

console.log('🔌 DB Config:', {
    ...config,
    connectionString: config.connectionString ? '***' : undefined,
    password: '***'
});

// Database connection configuration
export const pool = new Pool(config);

// Test database connection
export async function testConnection() {
    try {
        const client = await pool.connect();
        console.log('✅ Database connected successfully');
        client.release();
        return true;
    } catch (error) {
        console.error('❌ Database connection failed:', error.message);
        return false;
    }
}

// Execute a query
export async function query(text, params) {
    const start = Date.now();
    const res = await pool.query(text, params);
    const duration = Date.now() - start;
    console.log('Executed query', { text, duration, rows: res.rowCount });
    return res;
}

// Close the pool
export async function closePool() {
    await pool.end();
    console.log('Database connection pool closed');
}
