// Analytics market filter — request-scoped, zero-dependency.
// The UI sends `?gm=United States,Mexico` (GA country names). The HTTP layer
// stores the list in AsyncLocalStorage for the lifetime of that request, and
// the GA4 layer (ga4-rest.js runReport) transparently adds a
// `country IN (…)` filter to EVERY report it runs — totals, trend, every
// breakdown, drills, peaks, searches, journeys, outbound, channel mix — with
// zero changes to the individual query builders.
// (`gm`, not `market` — the media-monitoring section already uses `market`
// for its own tenant-DB market ids and the two must never collide.)

import { AsyncLocalStorage } from 'node:async_hooks';

export const marketALS = new AsyncLocalStorage();

// The selected GA country names, or null when unfiltered ("All markets").
export function currentMarkets() {
  const s = marketALS.getStore();
  return s?.countries?.length ? s.countries : null;
}

// The selected PLATFORM locale ids (?gml=1,2) — the DB's own market column.
// When set, platform queries filter by locale directly and the GA country
// filter is resolved from each locale's dominant reader country.
export function currentLocales() {
  const s = marketALS.getStore();
  return s?.locales?.length ? s.locales : null;
}

// Per-locale GA filter specs ({ country?, langPrefix? } rows, OR-combined) —
// set when a locale selection resolves. Needed because two locales can share
// a country (US English vs US Spanish): the browser-language prefix is what
// separates their GA traffic.
export function currentGaFilters() {
  const s = marketALS.getStore();
  return s?.gaFilters?.length ? s.gaFilters : null;
}

// Detected content language → GA4 languageCode prefix.
const LANG_CODES = {
  english: 'en', spanish: 'es', french: 'fr', german: 'de', italian: 'it',
  portuguese: 'pt', dutch: 'nl', polish: 'pl', turkish: 'tr', korean: 'ko',
  japanese: 'ja', chinese: 'zh', arabic: 'ar', russian: 'ru',
};
export function langCode(name) {
  return LANG_CODES[String(name || '').toLowerCase()] || null;
}

export function parseMarketsParam(raw) {
  return String(raw || '')
    .split(',')
    .map((x) => x.trim())
    .filter(Boolean)
    .slice(0, 12);
}

// Loose market-name aliases — used to match country names against email
// campaign titles and platform market labels ("MX Kona launch", "USA: …").
const ALIASES = {
  'united states': ['us', 'usa', 'u.s.', 'u.s.a', 'united states', 'america'],
  'mexico': ['mx', 'mexico', 'méxico', 'mex'],
  'canada': ['ca', 'canada', 'can'],
  'united kingdom': ['uk', 'gb', 'united kingdom', 'britain'],
  'germany': ['de', 'germany', 'deutschland', 'ger'],
  'france': ['fr', 'france', 'fra'],
  'spain': ['es', 'spain', 'españa', 'esp'],
  'italy': ['it', 'italy', 'italia', 'ita'],
  'brazil': ['br', 'brazil', 'brasil', 'bra'],
  'australia': ['au', 'australia', 'aus'],
  'japan': ['jp', 'japan', 'jpn'],
  'south korea': ['kr', 'korea', 'south korea'],
  'india': ['in', 'india', 'ind'],
  'china': ['cn', 'china', 'chn'],
  'netherlands': ['nl', 'netherlands', 'holland'],
  'switzerland': ['ch', 'switzerland'],
  'austria': ['at', 'austria'],
  'belgium': ['be', 'belgium'],
  'poland': ['pl', 'poland', 'polska'],
  'portugal': ['pt', 'portugal'],
  'sweden': ['se', 'sweden'],
  'norway': ['no', 'norway'],
  'denmark': ['dk', 'denmark'],
  'ireland': ['ie', 'ireland'],
  'turkey': ['tr', 'turkey', 'türkiye'],
  'russia': ['ru', 'russia'],
  'uae': ['ae', 'uae', 'united arab emirates', 'dubai'],
};

export function marketAliases(name) {
  const low = String(name || '').toLowerCase().trim();
  const list = ALIASES[low] ? [...ALIASES[low]] : [low];
  if (!list.includes(low)) list.push(low);
  return list;
}

// Does this text (campaign title, market label…) mention one of the selected
// markets? Short codes (≤3 chars) must match as whole words so "US" doesn't
// match "August"; longer names match as substrings.
export function textMatchesMarkets(text, countries) {
  const t = String(text || '').toLowerCase();
  if (!t) return false;
  for (const c of countries) {
    for (const alias of marketAliases(c)) {
      if (alias.length <= 3) {
        if (new RegExp(`(^|[^a-z])${alias.replace(/\./g, '\\.')}([^a-z]|$)`, 'i').test(t)) return true;
      } else if (t.includes(alias)) return true;
    }
  }
  return false;
}
