const ENABLED_VALUES = new Set(['1', 'true', 'yes'])

export function ensureDatabaseUrl(env: NodeJS.ProcessEnv = process.env) {
  const shouldBuildFromPostgres = ENABLED_VALUES.has(
    env.DATABASE_URL_FROM_POSTGRES?.trim().toLowerCase() ?? '',
  )

  if (!shouldBuildFromPostgres) {
    return env.DATABASE_URL
  }

  if (!env.POSTGRES_PASSWORD) {
    throw new Error('DATABASE_URL_FROM_POSTGRES is enabled but POSTGRES_PASSWORD is not set')
  }

  const user = env.POSTGRES_USER ?? 'postgres'
  const password = env.POSTGRES_PASSWORD
  const host = env.POSTGRES_HOST ?? 'postgres'
  const port = env.POSTGRES_PORT ?? '5432'
  const database = env.POSTGRES_DB ?? 'rentaldrivego'

  env.DATABASE_URL = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(database)}`

  return env.DATABASE_URL
}
