const { Pool } = require('pg');

const config = {
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    database: 'data',
    max: 10,
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 5000
};

const pool = new Pool(config);

pool.on('error', (err) => {
    console.error('[DB] Pool error:', err.message);
});

async function query(text, params) {
    const start = Date.now();
    try {
        const result = await pool.query(text, params);
        const duration = Date.now() - start;
        if (duration > 100) {
            console.warn(`[DB] Slow query (${duration}ms):`, text.substring(0, 80));
        }
        return result;
    } catch (err) {
        console.error('[DB] Query failed:', err.message, '| code:', err.code);
        throw err;
    }
}

async function getClient() {
    return await pool.connect();
}

async function initDb() {
    await pool.query('SELECT NOW()');
}

async function checkPostgres() {
    try {
        await pool.query('SELECT NOW()');
        return true;
    } catch {
        return false;
    }
}

module.exports = {
    pool,
    query,
    getClient,
    initDb,
    checkPostgres
};
