import { getCountryName, normalizeCountryCode } from "@/lib/countries";

const BASE_REGION_DEFINITIONS: Record<string, string[]> = {
  OPSA: ["ES", "PT"],
  DACH: ["AT", "DE", "CH"],
  OPSAB: ["FI", "SE", "NO", "NL", "DK", "BE", "LU"],
  OPUK: ["GB"],
  OPIT: ["IT"],
  OPFS: ["FR"],
  OPEL: ["BG", "HR", "CY", "CZ", "EE", "GR", "HU", "IE", "LV", "LT", "MT", "PL", "RO", "SK", "SI"],
};

const ALL_REGION_COUNTRIES = [...new Set(Object.values(BASE_REGION_DEFINITIONS).flat())].sort((a, b) =>
  a.localeCompare(b),
);

export const REGION_DEFINITIONS: Record<string, string[]> = {
  ...BASE_REGION_DEFINITIONS,
  OPEL: ALL_REGION_COUNTRIES,
};

function normalize(codes: string[]) {
  return [...new Set(codes.map((code) => normalizeCountryCode(code)).filter(Boolean))].sort();
}

export function getRegionMembers(regionCode: string) {
  return REGION_DEFINITIONS[regionCode] ?? [];
}

export function getRegionCodes() {
  return Object.keys(REGION_DEFINITIONS).sort((a, b) => a.localeCompare(b));
}

export function getAllRegionCountries() {
  return [...new Set(Object.values(REGION_DEFINITIONS).flat())].sort((a, b) =>
    a.localeCompare(b),
  );
}

export function getDashboardScopeForCountries(countryCodes: string[]) {
  const selected = normalize(countryCodes);
  if (selected.length === 0) return null;

  const matches = Object.entries(REGION_DEFINITIONS).filter(([, members]) =>
    selected.every((code) => members.includes(code)),
  );

  if (matches.length === 0) return null;
  matches.sort((a, b) => a[1].length - b[1].length);
  return matches[0]?.[0] ?? null;
}

export function getRegionLabel(regionCode: string) {
  const members = getRegionMembers(regionCode);
  if (members.length === 0) return regionCode;
  const names = members.map((code) => getCountryName(code));
  return `${regionCode}: ${names.join(", ")}`;
}

export function getRegionLabels(countryCodes: string[]) {
  const selected = normalize(countryCodes);
  if (selected.length === 0) return [];

  const exact = getDashboardScopeForCountries(selected);
  if (exact) {
    return [getRegionLabel(exact)];
  }

  return Object.entries(REGION_DEFINITIONS)
    .filter(([, members]) => members.every((code) => selected.includes(code)))
    .map(([region]) => getRegionLabel(region));
}
