import { Pool } from 'pg'
import { logger } from '../lib/logger'
import { requireDatabasePassword } from '../lib/secret-validation'

let pool: Pool | null = null

export function getDb(): Pool {
  if (!pool) {
    // Validate database password - fails fast if invalid in production
    const dbPassword = requireDatabasePassword()
    
    pool = new Pool({
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT || '5432', 10),
      database: process.env.DB_NAME || 'sankofa',
      user: process.env.DB_USER || 'postgres',
      password: dbPassword,
      max: 20,
      idleTimeoutMillis: 30000,
      connectionTimeoutMillis: 2000,
    })

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

  return pool
}

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

