import countries from "world-countries";

export interface CountryOption {
  code: string;
  name: string;
}

const normalizedCountries = countries
  .filter(country => country.cca2 && country.cca2.length === 2 && country.name?.common)
  .map(country => {
    const code = country.cca2.toUpperCase();
    const commonName = country.name.common;
    return {
      code,
      name: commonName,
      searchKeys: [commonName, country.name.official, ...(country.altSpellings ?? [])]
        .filter(Boolean)
        .map(entry => entry.toLowerCase()),
    };
  });

export const COUNTRY_OPTIONS: CountryOption[] = normalizedCountries
  .map(({ code, name }) => ({ code, name }))
  .sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));

const COUNTRY_NAME_BY_CODE = new Map(
  normalizedCountries.map(({ code, name }) => [code, name] as const)
);

const COUNTRY_CODE_BY_NAME = new Map<string, string>();
normalizedCountries.forEach(({ code, searchKeys }) => {
  searchKeys.forEach(key => {
    if (key && !COUNTRY_CODE_BY_NAME.has(key)) {
      COUNTRY_CODE_BY_NAME.set(key, code);
    }
  });
});

export function getCountryName(code?: string | null): string | undefined {
  if (!code) return undefined;
  return COUNTRY_NAME_BY_CODE.get(code.toUpperCase());
}

export function getCountryCodeByName(name?: string | null): string | undefined {
  if (!name) return undefined;
  return COUNTRY_CODE_BY_NAME.get(name.toLowerCase());
}
