require('dotenv').config();
const { Client } = require('pg');

const config = {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    port: process.env.DB_PORT,
};

console.log('--- Database Connection Diagnostic ---');
console.log(`Host: ${config.host}`);
console.log(`User: ${config.user}`);
console.log(`Database: ${config.database}`);
console.log(`Port: ${config.port}`);
console.log(`Password: ${config.password ? '**** (Set)' : '(Not Set!)'}`);
console.log('--------------------------------------');

const client = new Client(config);

(async () => {
    try {
        await client.connect();
        console.log('✅ Connection Successful!');
        const res = await client.query('SELECT current_user, current_database()');
        console.log('Connected as:', res.rows[0]);
        await client.end();
    } catch (err) {
        console.error('❌ Connection Failed!');
        console.error('Error Code:', err.code);
        console.error('Message:', err.message);
        if (err.code === '28P01') {
            console.log('\nPossible causes for 28P01 (Auth Failed):');
            console.log('1. Wrong password.');
            console.log('2. Wrong username.');
            console.log('3. User exists but has no password set in DB.');
        }
        await client.end();
        process.exit(1);
    }
})();
