/**
 * config/publicBaseUrl.js
 *
 * Single source of truth for the canonical public origin used in
 * outbound emails (verification, password reset, takedown letters),
 * 2FA issuer names, and alert detail.
 *
 * Accepts (in priority order):
 *   1. PUBLIC_BASE_URL
 *   2. APP_URL
 *   3. http://localhost:$PORT  (dev fallback)
 *
 * The chosen value is also asserted at app startup in production
 * (see config/assertProductionEnv.js): if the env vars are both
 * missing, the process refuses to boot instead of silently shipping
 * emails with `undefined/...` URLs.
 */

'use strict';

let _cached = null;

function publicBaseUrl() {
  if (_cached) return _cached;
  const raw = (process.env.PUBLIC_BASE_URL || process.env.APP_URL || '').trim();
  if (raw) {
    _cached = raw.replace(/\/+$/, '');          // strip trailing slash
    return _cached;
  }
  // Dev fallback — never used in production because assertProductionEnv
  // refuses to boot without PUBLIC_BASE_URL.
  const port = process.env.PORT || 3000;
  _cached = `http://localhost:${port}`;
  return _cached;
}

function resetCache() { _cached = null; }        // for tests

module.exports = { publicBaseUrl, resetCache };
