/**
 * Resolve the public URL of a request, respecting reverse-proxy headers.
 * In production we run behind Traefik on satra → externally vreaudigital.ro.
 * The container sees `host=localhost:4321` so `url.origin` is wrong; we trust
 * X-Forwarded-Proto and X-Forwarded-Host as set by Traefik.
 */
export function publicOrigin(request: Request, fallback: URL): string {
  const proto = request.headers.get('x-forwarded-proto') || fallback.protocol.replace(':', '');
  const host = request.headers.get('x-forwarded-host') || request.headers.get('host') || fallback.host;
  if (!host || host.startsWith('localhost') || host.startsWith('127.')) {
    return 'https://vreaudigital.ro';
  }
  return `${proto}://${host}`;
}

export function publicUrl(request: Request, fallback: URL): string {
  return `${publicOrigin(request, fallback)}${fallback.pathname}${fallback.search}`;
}
