import pg from 'pg'

const { Pool } = pg

export function getDatabaseUrl() {
  const databaseUrl = process.env.DATABASE_URL
  if (!databaseUrl) {
    throw new Error('DATABASE_URL is required for server database access.')
  }
  return databaseUrl
}

export function createPool() {
  return new Pool({
    connectionString: getDatabaseUrl(),
    max: Number(process.env.DB_POOL_MAX ?? 10),
  })
}

export async function waitForDatabase(pool, attempts = 30) {
  let lastError
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
    try {
      await pool.query('select 1')
      return
    } catch (error) {
      lastError = error
      await new Promise((resolve) => setTimeout(resolve, Math.min(5000, attempt * 500)))
    }
  }
  throw lastError
}
