import { Pool, PoolConfig } from 'pg';
import * as dotenv from 'dotenv';
import { logger } from '../utils/logger';

dotenv.config();

let pool: Pool | null = null;

export interface DatabaseConfig {
  connectionString?: string;
  host?: string;
  port?: number;
  database?: string;
  user?: string;
  password?: string;
  min?: number;
  max?: number;
}

export function getDatabasePool(): Pool {
  if (pool) {
    return pool;
  }

  const config: PoolConfig = {
    connectionString: process.env.DATABASE_URL,
    min: parseInt(process.env.DATABASE_POOL_MIN || '2', 10),
    max: parseInt(process.env.DATABASE_POOL_MAX || '10', 10),
  };

  // If connectionString is not provided, use individual config
  if (!config.connectionString) {
    config.host = process.env.DB_HOST || 'localhost';
    config.port = parseInt(process.env.DB_PORT || '5432', 10);
    config.database = process.env.DB_NAME || 'explorer_db';
    config.user = process.env.DB_USER || 'postgres';
    config.password = process.env.DB_PASSWORD || '';
  }

  pool = new Pool(config);

  pool.on('error', (err) => {
    logger.error('Unexpected error on idle database client', err);
  });

  return pool;
}

export async function closeDatabasePool(): Promise<void> {
  if (pool) {
    await pool.end();
    pool = null;
  }
}
