/**
 * Country → business area, for the "Sign-ups by area" breakdown.
 *
 * The mapping is ported verbatim from KCGM's own seed
 * (`KCGM-Dashboard/packages/db/seed/02_reference.sql`) so the buckets match what
 * the business already uses. It is a TS constant rather than a DB lookup because
 * core's `kcgm_region_map` table exists but is never populated or read — see the
 * note below.
 *
 * UNMAPPED COUNTRIES GO TO EU_UK_ROW
 *
 * This used to route them to a separate `Unmapped` bucket so the unclassified
 * tail stayed visible. That was the wrong reading of the bucket: the third area
 * is "EU / UK / ROW", and ROW *is* rest-of-world — so a country that is neither
 * India nor SEAP belongs there by definition, not in a fourth category. Matching
 * KCGM's own `kcgm_region_for()` default also keeps the two dashboards
 * comparable.
 *
 * `No Country Info` is still its own bucket, and is a different thing: it means
 * the member has no country recorded at all, which is a data-quality signal
 * rather than a geography.
 */

import { normaliseCountry } from "./charts/countryNames";

export const AREAS = [
  "India",
  "SEAP",
  "EU_UK_ROW",
  "No Country Info",
] as const;

export type Area = (typeof AREAS)[number];

/** Normalised country name → area. Keys are pre-normalised at module load. */
const AREA_BY_COUNTRY: Map<string, Area> = new Map(
  (
    [
      ["India", "India"],

      ["Australia", "SEAP"],
      ["New Zealand", "SEAP"],
      ["Indonesia", "SEAP"],
      ["Singapore", "SEAP"],
      ["Malaysia", "SEAP"],
      ["Thailand", "SEAP"],
      ["Philippines", "SEAP"],
      ["Vietnam", "SEAP"],
      ["China", "SEAP"],

      ["United Kingdom", "EU_UK_ROW"],
      ["UK", "EU_UK_ROW"],
      ["Ireland", "EU_UK_ROW"],
      ["Spain", "EU_UK_ROW"],
      ["France", "EU_UK_ROW"],
      ["Germany", "EU_UK_ROW"],
      ["Italy", "EU_UK_ROW"],
      ["Portugal", "EU_UK_ROW"],
      ["United States", "EU_UK_ROW"],
      ["USA", "EU_UK_ROW"],
      ["Canada", "EU_UK_ROW"],
      ["United Arab Emirates", "EU_UK_ROW"],
    ] as Array<[string, Area]>
  ).map(([country, area]) => [normaliseCountry(country), area]),
);

/**
 * Area for a country name; anything not explicitly mapped is rest-of-world.
 *
 * Matching reuses `normaliseCountry`, so casing, punctuation, diacritics and a
 * leading "The" don't cause a miss — "the netherlands" and "Netherlands" resolve
 * identically.
 *
 * Only a blank/absent country gives `No Country Info`. A country we simply have
 * no explicit row for is still a real country, so it lands in EU_UK_ROW.
 */
export function areaOf(country: string | null | undefined): Area {
  const raw = (country ?? "").trim();
  if (raw === "") return "No Country Info";
  return AREA_BY_COUNTRY.get(normaliseCountry(raw)) ?? "EU_UK_ROW";
}

/** Countries the mapping covers, for surfacing coverage in the UI. */
export const MAPPED_COUNTRY_COUNT = AREA_BY_COUNTRY.size;
