import { Pool } from 'pg';
import { config } from './env';
import logger from '../utils/logger';

// Create connection pool
const poolConfig = config.database.url 
  ? { connectionString: config.database.url }
  : {
      host: config.database.host,
      port: config.database.port,
      database: config.database.name,
      user: config.database.user,
      password: config.database.password,
    };

const pool = new Pool({
  ...poolConfig,
  max: 20, // Maximum number of clients in the pool
  idleTimeoutMillis: 30000, // Close idle clients after 30 seconds
  connectionTimeoutMillis: 10000, // Return an error after 10 seconds if connection could not be established
  query_timeout: 30000, // Query timeout of 30 seconds
  statement_timeout: 30000, // Statement timeout of 30 seconds
});

// Test database connection
pool.on('connect', () => {
  logger.info('Connected to PostgreSQL database');
});

pool.on('error', (err: Error) => {
  logger.error('Unexpected error on idle client', err);
  process.exit(-1);
});

// Graceful shutdown
process.on('SIGINT', async () => {
  logger.info('Shutting down database pool...');
  await pool.end();
  process.exit(0);
});

export default pool; 