const DEFAULTS = Object.freeze({ max: 20, min: 0, connectionTimeoutMillis: 5000, idleTimeoutMillis: 30000, queryTimeout: 15000, }); function positiveInt(value, fallback, minimum = 0) { const parsed = Number.parseInt(String(value ?? ''), 10); return Number.isInteger(parsed) && parsed >= minimum ? parsed : fallback; } /** Return DATABASE_URL or throw an actionable startup error. */ export function databaseUrlFromEnv(env = process.env) { const url = String(env.DATABASE_URL || '').trim(); if (!url) { const error = new Error('DATABASE_URL is required'); error.code = 'DB_NOT_CONFIGURED'; throw error; } return url; } /** Build a pg.Pool-compatible configuration from environment variables. */ export function databaseConfigFromEnv(env = process.env) { const max = positiveInt(env.DATABASE_MAX_CONNS, DEFAULTS.max, 1); const min = positiveInt(env.DATABASE_MIN_CONNS, DEFAULTS.min, 0); if (min > max) { throw new Error('DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS'); } return { connectionString: databaseUrlFromEnv(env), max, min, connectionTimeoutMillis: positiveInt( env.DATABASE_CONNECT_TIMEOUT_MS, DEFAULTS.connectionTimeoutMillis, 1 ), idleTimeoutMillis: positiveInt( env.DATABASE_IDLE_TIMEOUT_MS, DEFAULTS.idleTimeoutMillis, 0 ), query_timeout: positiveInt(env.DATABASE_QUERY_TIMEOUT_MS, DEFAULTS.queryTimeout, 1), ssl: /^(true|require|1)$/i.test(String(env.DATABASE_SSL || '')) ? { rejectUnauthorized: !/^(true|1)$/i.test(String(env.DATABASE_SSL_ALLOW_INVALID || '')) } : undefined, }; } export { DEFAULTS as DATABASE_DEFAULTS };