import { recordAffClick } from "../api/agent"

const ATTRIBUTION_KEY = "qycw_aff_attribution"
const CLICK_SESSION_PREFIX = "qycw_aff_click:"

export type AffiliateAttribution = {
  ref: string
  coupon?: string
  utm_source?: string
  utm_medium?: string
  utm_campaign?: string
  utm_content?: string
  utm_term?: string
  landing_url: string
  captured_at: string
}

function readParam(params: URLSearchParams, key: string) {
  const value = params.get(key)?.trim()
  return value || undefined
}

export function getStoredAffiliateAttribution(): AffiliateAttribution | null {
  try {
    const raw = localStorage.getItem(ATTRIBUTION_KEY)
    if (!raw) return null
    const data = JSON.parse(raw) as AffiliateAttribution
    return data?.ref ? data : null
  } catch {
    return null
  }
}

export function captureAffiliateAttribution(search: string, href: string) {
  const params = new URLSearchParams(search)
  const ref = readParam(params, "ref")
  if (!ref) return

  const attribution: AffiliateAttribution = {
    ref,
    coupon: readParam(params, "coupon"),
    utm_source: readParam(params, "utm_source"),
    utm_medium: readParam(params, "utm_medium"),
    utm_campaign: readParam(params, "utm_campaign"),
    utm_content: readParam(params, "utm_content"),
    utm_term: readParam(params, "utm_term"),
    landing_url: href,
    captured_at: new Date().toISOString(),
  }

  localStorage.setItem(ATTRIBUTION_KEY, JSON.stringify(attribution))

  const clickKey = `${CLICK_SESSION_PREFIX}${[
    attribution.ref,
    attribution.coupon || "",
    attribution.utm_source || "",
    attribution.utm_medium || "",
    attribution.utm_campaign || "",
    attribution.utm_content || "",
    attribution.utm_term || "",
    attribution.landing_url,
  ].join("|")}`
  if (sessionStorage.getItem(clickKey)) return
  sessionStorage.setItem(clickKey, "1")

  recordAffClick(ref, {
    ref,
    coupon: attribution.coupon,
    utm_source: attribution.utm_source,
    utm_medium: attribution.utm_medium,
    utm_campaign: attribution.utm_campaign,
    utm_content: attribution.utm_content,
    utm_term: attribution.utm_term,
    landing_url: href,
  }).catch(() => {
    sessionStorage.removeItem(clickKey)
  })
}
