import pkg from 'pg';
import dotenv from 'dotenv';
import logger from '../utils/logger.js';

const { Pool } = pkg;
dotenv.config();

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  min: parseInt(process.env.DATABASE_POOL_MIN || '5', 10),
  max: parseInt(process.env.DATABASE_POOL_MAX || '20', 10),
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 5000,
});

pool.on('error', (error) => {
  logger.error({
    message: 'Unexpected error on idle client',
    error: error.message,
    stack: error.stack
  });
});

pool.on('connect', () => {
  logger.debug({ message: 'New database connection established' });
});

export { pool };
