/**
 * Coupon-poaching guardrail.
 *
 * Detects affiliates driving traffic via coupon-aggregator sites (e.g.
 * couponmama.co.il, savii.co.il, zap.co.il/coupons). This traffic arrives
 * with a known set of coupon-site referer hostnames. These sites typically
 * list deals without an affiliate agreement, which inflates attributed
 * commissions unfairly.
 *
 * The coupon-site blocklist is checked against the referer host.
 * Hits get flagged COUPON_POACHING and setCookie=false — no attribution.
 */

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

/** Default coupon aggregator domains (case-insensitive partial match on hostname). */
const DEFAULT_COUPON_DOMAINS = [
  'couponmama',
  'savii.co.il',
  'groupon',
  'vouchercloud',
  'zap.co.il/coupons',
  'hotukdeals',
  'dealspotr',
  'coupert',
  'honey',
  'piggyback',
  'cashback',
]

/**
 * Evaluate coupon-poaching.
 *
 * @param refererUrl      - Raw Referer header value.
 * @param couponDomains   - Additional coupon domains to block (merged with defaults).
 */
export function evaluateCouponPoaching(
  refererUrl: string,
  couponDomains: string[] = [],
): GuardResult {
  if (!refererUrl) {
    return { isSuspicious: false, codes: [], setCookie: true }
  }

  let url: URL
  try {
    url = new URL(refererUrl)
  } catch {
    return { isSuspicious: false, codes: [], setCookie: true }
  }

  const host = url.hostname.toLowerCase() + url.pathname.toLowerCase()
  const allDomains = [...DEFAULT_COUPON_DOMAINS, ...couponDomains]
  const isCouponSite = allDomains.some((d) => host.includes(d.toLowerCase()))

  if (isCouponSite) {
    return {
      isSuspicious: true,
      codes: ['COUPON_POACHING'],
      setCookie: false,
    }
  }

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