import { getRegionCodes, getRegionLabel, getRegionMembers } from "@/lib/regions";

export type UploadScope = {
  code: string;
  countries: string[];
};

export function parseUploadScope(raw: FormDataEntryValue | null): UploadScope | null {
  if (typeof raw !== "string") return null;

  const code = raw.trim().toUpperCase();
  if (!code) return null;

  if (!getRegionCodes().includes(code)) {
    throw new Error(`Unknown dashboard scope: ${code}`);
  }

  return {
    code,
    countries: getRegionMembers(code).map((country) => country.toUpperCase()),
  };
}

export function ensureUploadScopeCountries(countryCodes: string[], scope: UploadScope | null) {
  if (!scope) return;

  const denied = [...new Set(countryCodes.map((country) => country.trim().toUpperCase()).filter(Boolean))].filter(
    (country) => !scope.countries.includes(country),
  );

  if (denied.length === 0) return;

  throw new Error(
    `Scope ${scope.code} (${getRegionLabel(scope.code)}) only allows ${scope.countries.join(
      ", ",
    )}. Found: ${denied.join(", ")}`,
  );
}

