/**
 * URL normalisation helpers shared across the conversion dedup pipeline.
 *
 * normalizePageUrl is used by:
 *   - conversion-resolver.ts  (write-time form dedup)
 *   - backfill-dedup/route.ts (historical form dedup makeWinKey)
 *   - auto-backfill.ts        (pre-create existence check)
 *
 * All three callers must stay in sync; any change to the algorithm
 * invalidates existing backfill-dedup keys. Change only with a
 * coordinated backfill re-run.
 */

/**
 * Reduce a full page URL to a canonical host+path string suitable for
 * cross-path dedup. Strips protocol, lowercases host, drops leading
 * "www.", drops query string and fragment, normalises trailing slash.
 *
 * Both t.source.js and form-phone.js store window.location.href verbatim
 * so in practice the raw values match; normalization handles edge cases
 * (http vs https, www vs non-www, hash fragments, UTM params).
 */
export function normalizePageUrl(raw: string): string {
  try {
    const u = new URL(raw);
    const host = u.hostname.toLowerCase().replace(/^www\./, "");
    let path = u.pathname;
    if (path.length > 1 && path.endsWith("/")) path = path.slice(0, -1);
    return `${host}${path}`;
  } catch {
    // Malformed URL: lowercase and strip query+hash+trailing slash.
    return raw.toLowerCase().replace(/[?#].*$/, "").replace(/\/+$/, "");
  }
}
