// Session 13 — Africa geo-restriction set. The pricing component
// relies on isAfricanCountry() to gate the $4.99 tier. Tests pin
// the membership list so adding/removing a country is a visible,
// reviewed change rather than a silent edit.

const fs = require('fs');
const path = require('path');

const FILE = path.join(__dirname, '..', '..', 'web', 'src', 'lib', 'locales.ts');
const source = fs.readFileSync(FILE, 'utf8');

// Pull the AFRICAN_COUNTRIES set out of the TS source by regex. Tests
// the values, not the implementation — if the format changes, the
// failure is on the parse and tells us to update the test loader.
function parseAfricanCountries() {
  const start = source.indexOf('AFRICAN_COUNTRIES');
  if (start === -1) throw new Error('AFRICAN_COUNTRIES not found in locales.ts');
  const slice = source.slice(start, start + 4000);
  const codes = [...slice.matchAll(/'([A-Z]{2})'/g)].map((m) => m[1]);
  return new Set(codes);
}

function reimplementIsAfrican(set) {
  return (code) => {
    if (!code) return false;
    return set.has(String(code).toUpperCase());
  };
}

describe('AFRICAN_COUNTRIES gate (Session 13)', () => {
  const COUNTRIES = parseAfricanCountries();
  const isAfricanCountry = reimplementIsAfrican(COUNTRIES);

  test('covers all 54 sovereign African nations', () => {
    expect(COUNTRIES.size).toBeGreaterThanOrEqual(50);
  });

  test('includes the major mobile-betting markets', () => {
    const required = ['NG', 'KE', 'ZA', 'GH', 'TZ', 'UG', 'EG', 'MA'];
    for (const code of required) expect(COUNTRIES.has(code)).toBe(true);
  });

  test('rejects non-African codes', () => {
    const notAfrican = ['US', 'GB', 'CA', 'IN', 'BR', 'JP', 'DE', 'AU', 'CN', 'FR'];
    for (const code of notAfrican) expect(COUNTRIES.has(code)).toBe(false);
  });

  test('isAfricanCountry — case-insensitive', () => {
    expect(isAfricanCountry('ng')).toBe(true);
    expect(isAfricanCountry('Ng')).toBe(true);
    expect(isAfricanCountry('NG')).toBe(true);
  });

  test('isAfricanCountry — degrades closed on empty/null/undefined', () => {
    expect(isAfricanCountry('')).toBe(false);
    expect(isAfricanCountry(null)).toBe(false);
    expect(isAfricanCountry(undefined)).toBe(false);
  });

  test('isAfricanCountry — degrades closed on unknown codes', () => {
    expect(isAfricanCountry('ZZ')).toBe(false);
    expect(isAfricanCountry('XX')).toBe(false);
  });
});
