/**
 * Origin for public links served by this app (no trailing slash, no `/api`).
 * Uses PUBLIC_BASE_URL / APP_BASE_URL when set; otherwise infers from proxy headers
 * when Host is not loopback (so production works without env if Nginx sends standard headers).
 */
function resolvePublicBaseUrl(req) {
  const envBase = (process.env.PUBLIC_BASE_URL || process.env.APP_BASE_URL || '')
    .trim()
    .replace(/\/$/, '');
  if (envBase) return envBase;

  const rawHost = (req.get('x-forwarded-host') || req.get('host') || '').split(',')[0].trim();
  const isLoopback =
    !rawHost ||
    /^localhost(:\d+)?$/i.test(rawHost) ||
    /^127\.\d+\.\d+\.\d+(:\d+)?$/i.test(rawHost) ||
    /^\[::1\](:\d+)?$/i.test(rawHost);

  if (isLoopback) {
    if (process.env.NODE_ENV === 'production') {
      return '';
    }
    const p = process.env.PORT || 3000;
    return `http://localhost:${String(p)}`;
  }

  let proto = (req.get('x-forwarded-proto') || '').split(',')[0].trim();
  if (!proto && req.secure) proto = 'https';
  if (!proto) proto = req.protocol || 'https';
  if (proto !== 'http' && proto !== 'https') proto = 'https';

  return `${proto}://${rawHost}`.replace(/\/$/, '');
}

module.exports = { resolvePublicBaseUrl };
