import pkg from 'pg';
import dotenv from 'dotenv';
const { Pool } = pkg;

// Load environment variables
dotenv.config();

const dbCache = {};

function getSubDbConnection(dbName) {
  if (!dbName) throw new Error('Missing dbName');
  if (dbCache[dbName]) return dbCache[dbName];

  const connection = new Pool({
    host: process.env.DB_HOST || 'localhost',
    port: process.env.DB_PORT || 5432,
    user: process.env.DB_USER || 'postgres',
    password: process.env.DB_PASSWORD || '12345',
    database: dbName,
    max: 20, // Maximum pool size
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000, // Fail fast on connection issues
  });

  // ✅ Add error handler for the pool
  connection.on('error', (err, client) => {
    console.error('Unexpected pool error:', err);
    console.error('Database:', dbName);
  });

  console.log(`Created pool for database: ${dbName}`);

  dbCache[dbName] = connection;
  return connection;
}

export default getSubDbConnection;
