const { getConfig, normalizeUrl } = require('./config')
const { resolveCmsHttpBaseUrl } = require('./cms-http-base')

/** @param {string[]} names */
function firstNonEmptyEnvTrimmed(...names) {
  for (const name of names) {
    const v = process.env[name]
    if (v != null && String(v).trim() !== '') return String(v).trim()
  }
  return null
}

/**
 * Cloud Functions (or other) origin for admin list routes, e.g.
 * `https://us-central1-PROJECT.cloudfunctions.net` — not the CDN `cmsUrl`.
 * Env wins over ~/.bild.json.
 * @returns {string|null}
 */
function getCmsFunctionsBaseUrl() {
  const fromEnv = firstNonEmptyEnvTrimmed('BILD_CMS_FUNCTIONS_URL')
  if (fromEnv) return normalizeUrl(fromEnv)
  const c = getConfig()
  const v = c.cmsFunctionsBaseUrl
  if (v != null && String(v).trim() !== '') return normalizeUrl(String(v).trim())
  return null
}

/**
 * Value for `database-url` header on admin routes (trim only; keep trailing slash).
 * @returns {string|null}
 */
function getCmsDatabaseUrl() {
  const fromEnv = firstNonEmptyEnvTrimmed('BILD_CMS_DATABASE_URL')
  if (fromEnv) return fromEnv
  const c = getConfig()
  const v = c.cmsDatabaseUrl
  if (v != null && String(v).trim() !== '') return String(v).trim()
  return null
}

/**
 * Override path segment `/api/admin/users/<this>/apps` when it must differ from JWT `sub`.
 * @returns {string|null}
 */
function getCmsListAppsUserIdOverride() {
  const fromEnv = firstNonEmptyEnvTrimmed('BILD_CMS_LIST_APPS_USER_ID')
  if (fromEnv) return fromEnv
  const c = getConfig()
  const v = c.cmsListAppsUserId
  if (v != null && String(v).trim() !== '') return String(v).trim()
  return null
}

/**
 * Mimic browser/admin requests: Accept + optional RTDB URL header.
 * @returns {Record<string, string>}
 */
function adminListHeaders() {
  /** @type {Record<string, string>} */
  const h = { Accept: 'application/json' }
  const db = getCmsDatabaseUrl()
  if (db) h['database-url'] = db
  return h
}

/**
 * Base URL for authenticated CMS HTTP API (library, banners, contents, uploads, etc.).
 * Prefer {@link getCmsFunctionsBaseUrl} when set; otherwise hosted `cmsUrl`.
 * @returns {string}
 */
function resolveCmsApiBaseUrl() {
  const fn = getCmsFunctionsBaseUrl()
  if (fn) return fn
  return resolveCmsHttpBaseUrl(getConfig().cmsUrl)
}

module.exports = {
  getCmsFunctionsBaseUrl,
  getCmsDatabaseUrl,
  getCmsListAppsUserIdOverride,
  adminListHeaders,
  resolveCmsApiBaseUrl,
}
