import type { NextRequest } from 'next/server'

/**
 * The product's canonical public domain. Single source of truth — the domain
 * is never spelled out again anywhere in the app (Nash, 2026-09-07: a wrong
 * domain was reaching real users through emailed links; "we use only
 * heavyhaulagent.com").
 *
 * This is the canonical/brand URL used for SEO metadata and for illustrative
 * links in marketing copy. Links generated at request time (invites, intake
 * responses) go through `publicOrigin` instead, so they keep working on
 * staging and localhost.
 */
export const SITE_URL = 'https://heavyhaulagent.com'
export const SITE_DOMAIN = SITE_URL.replace(/^https?:\/\//, '')
export const SUPPORT_EMAIL = `support@${SITE_DOMAIN}`

/**
 * Public origin for links we hand out (invite links, intake responses).
 * Behind a reverse proxy `req.nextUrl.origin` is the internal address
 * (e.g. http://localhost:8001), so an explicit NEXT_PUBLIC_APP_URL wins.
 */
export function publicOrigin(req: NextRequest): string {
  const configured = process.env.NEXT_PUBLIC_APP_URL?.trim().replace(/\/+$/, '')
  return configured || req.nextUrl.origin
}

/**
 * Keep navigation on the browser's current host. Behind the production reverse
 * proxy, req.url can be http://localhost:8001 even when the visitor is on the
 * public site. A relative Location header avoids leaking that internal host.
 */
export function sameSiteRedirect(path: string): Response {
  if (!path.startsWith('/') || path.startsWith('//')) {
    throw new Error('Redirect target must be a local path')
  }
  return new Response(null, { status: 307, headers: { Location: path } })
}
