/**
 * Resolve the canonical site URL using a cascade that works across every
 * environment (local dev, Vercel previews, production).
 *
 * Order of preference:
 *   1. NEXT_PUBLIC_SITE_URL  — explicit brand/marketing URL (e.g. https://echo.stillwell.cloud)
 *   2. AUTH_URL              — set in production for Auth.js; identical to canonical host
 *   3. VERCEL_URL            — auto-injected on every Vercel deploy (e.g. *.vercel.app)
 *   4. http://localhost:3000 — final fallback for local dev
 *
 * Never returns a hardcoded third-party domain the team might not own.
 */
export function getSiteUrl(): string {
  const explicit = process.env.NEXT_PUBLIC_SITE_URL || process.env.AUTH_URL;
  if (explicit) return stripTrailingSlash(explicit);

  if (process.env.VERCEL_URL) {
    return `https://${process.env.VERCEL_URL}`;
  }

  return "http://localhost:3000";
}

/**
 * Resolve the site URL from an incoming request first (most reliable — whatever
 * host the user actually hit), falling back to env vars.
 *
 * Prefer this in API routes where you're generating links the user will follow
 * (password reset emails, invite links, QR codes, etc.), so links always point
 * back to the same domain the request came from.
 */
export function getSiteUrlFromRequest(req: Request): string {
  try {
    const url = new URL(req.url);
    const forwardedHost = req.headers.get("x-forwarded-host");
    const forwardedProto = req.headers.get("x-forwarded-proto");
    if (forwardedHost) {
      const proto = forwardedProto || url.protocol.replace(":", "") || "https";
      return `${proto}://${forwardedHost}`;
    }
    return url.origin;
  } catch {
    return getSiteUrl();
  }
}

/**
 * Extract a human-readable hostname (e.g. "echo.stillwell.cloud") from any
 * URL string. Useful for email footers and marketing copy so the displayed
 * brand domain always matches the link target.
 */
export function getSiteHostname(siteUrl: string = getSiteUrl()): string {
  try {
    return new URL(siteUrl).hostname;
  } catch {
    return siteUrl;
  }
}

function stripTrailingSlash(url: string): string {
  return url.endsWith("/") ? url.slice(0, -1) : url;
}
