const { Pool } = require('pg');
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../../..', '.env') });

// Database configuration
const dbConfig = {
    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 || 5432,
    ssl: process.env.DB_SSL === 'true',
    // Pin the session timezone to business time (see docs/TIME.md) — the
    // metrics SQL window anchors (CURRENT_DATE etc.) must mean Chicago dates.
    options: '-c TimeZone=America/Chicago',
    // Add performance optimizations
    max: 10, // connection pool max size
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 60000
};

// Create a single pool instance to be reused
const pool = new Pool(dbConfig);

// Add event handlers for pool
pool.on('error', (err, client) => {
    console.error('Unexpected error on idle client', err);
});

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

async function closePool() {
    await pool.end();
}

module.exports = {
    dbConfig,
    getConnection,
    closePool
}; 