/**
 * Cookie-stuffing guardrail.
 *
 * Cookie stuffing is when an affiliate injects a referral cookie without the
 * user actually navigating to the site (e.g. via an invisible iframe, XHR, or
 * programmatic fetch). The Sec-Fetch-Mode and Sec-Fetch-Dest headers reliably
 * distinguish top-level navigation from programmatic requests.
 *
 * A legitimate referral arrives as a top-level document navigation:
 *   Sec-Fetch-Mode: navigate
 *   Sec-Fetch-Dest: document
 *
 * Anything else (cors, no-cors, same-origin with Sec-Fetch-Dest: empty) is
 * suspicious.
 *
 * Note: when Sec-Fetch-Mode is absent (old browsers, curl, server-side proxies),
 * we allow the request — false positives in ambiguous cases are costlier than
 * missed detections.
 */

import type { GuardResult } from './brand-keyword.js';

export type SecFetchHeaders = {
  secFetchMode: string | null;
  secFetchDest: string | null;
  secFetchSite: string | null;
};

/**
 * Evaluate cookie-stuffing signals.
 *
 * @param headers - Sec-Fetch-* header values (null = header absent).
 */
export function evaluateCookieStuffing(headers: SecFetchHeaders): GuardResult {
  const { secFetchMode } = headers;

  // Header absent → ambiguous; allow (avoid false positives).
  if (!secFetchMode) {
    return { isSuspicious: false, codes: [], setCookie: true };
  }

  if (secFetchMode !== 'navigate') {
    return {
      isSuspicious: true,
      codes: ['COOKIE_STUFFING'],
      setCookie: false,
    };
  }

  return { isSuspicious: false, codes: [], setCookie: true };
}
