/**
 * Cloaking guardrail.
 *
 * Cloaking is when an affiliate redirects real users through an intermediate
 * page to hide the original traffic source from the merchant. Signals:
 *
 *   1. USER_AGENT_MISMATCH — User-Agent is a known bot/scraper UA but the
 *      request arrives as a navigating browser (Sec-Fetch-Mode: navigate).
 *      Consistent with affiliates running headless browsers to simulate clicks.
 *
 *   2. REFERER_REDIRECT_CHAIN — Referer is the affiliate's own domain but the
 *      cf-connecting-ip country doesn't match any IL origin.
 *      (Deferred — requires cross-signal correlation; stub returns false.)
 *
 * setCookie=false for bot-UA cloaking. NO_REFERER is suspicious but still
 * sets cookie (handled by referer-eval).
 */

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

const BOT_UA_PATTERNS = [
  /headlesschrome/i,
  /phantomjs/i,
  /selenium/i,
  /puppeteer/i,
  /playwright/i,
  /scrapy/i,
  /python-requests/i,
  /go-http-client/i,
  /curl\//i,
  /wget\//i,
  /libwww/i,
  /java\//i,
  /okhttp\//i,
];

/**
 * Evaluate cloaking signals.
 *
 * @param userAgent     - User-Agent header value.
 * @param secFetchMode  - Sec-Fetch-Mode header value (null if absent).
 */
export function evaluateCloaking(
  userAgent: string,
  secFetchMode: string | null,
): GuardResult {
  if (!userAgent) {
    return { isSuspicious: false, codes: [], setCookie: true };
  }

  const isBotUa = BOT_UA_PATTERNS.some((re) => re.test(userAgent));

  // Bot UA + navigate mode = headless browser simulating click → cloaking.
  if (isBotUa && secFetchMode === 'navigate') {
    return {
      isSuspicious: true,
      codes: ['CLOAKING'],
      setCookie: false,
    };
  }

  // Bot UA without navigate header → likely legitimate crawler, not click fraud.
  if (isBotUa) {
    return {
      isSuspicious: true,
      codes: ['BOT_UA'],
      setCookie: false,
    };
  }

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