import { Pool } from 'pg'

let pool: Pool | null = null

export function initializeDatabase(): Pool {
  if (pool) return pool

  const postgresUrl = process.env.DATABASE_URL

  if (!postgresUrl) {
    throw new Error(
      'DATABASE_URL environment variable not configured. Set it to: postgres://user:password@host:port/database'
    )
  }

  pool = new Pool({
    connectionString: postgresUrl,
    max: parseInt(process.env.DB_POOL_SIZE ?? '20', 10),
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000,
  })

  pool.on('error', (error) => {
    console.error('[Database] Unexpected pool error:', error)
  })

  return pool
}

export function getDatabase(): Pool {
  if (!pool) {
    throw new Error('Database not initialized. Call initializeDatabase() first.')
  }
  return pool
}

export async function testDatabaseConnection(): Promise<void> {
  const db = getDatabase()
  try {
    const result = await db.query('SELECT NOW()')
    console.log('[Database] Connection successful:', result.rows[0].now)
  } catch (error) {
    console.error('[Database] Connection failed:', error)
    throw error
  }
}

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