import { countries } from "./countries";

const SLUG_PREFIX = "send-money-to-";

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

// e.g. "AL" -> "send-money-to-albania"
export function countrySlug(code: string): string | null {
  const match = countries.find(
    (c) => c.code.toLowerCase() === code.toLowerCase()
  );
  return match ? `${SLUG_PREFIX}${slugify(match.country)}` : null;
}

// Accepts either the canonical "send-money-to-albania" slug or a bare
// legacy code like "al", and resolves it back to the country code.
export function codeFromSlug(slug: string): string | null {
  const normalized = slug.toLowerCase();
  const withoutPrefix = normalized.startsWith(SLUG_PREFIX)
    ? normalized.slice(SLUG_PREFIX.length)
    : normalized;

  const byName = countries.find((c) => slugify(c.country) === withoutPrefix);
  if (byName) return byName.code;

  const byCode = countries.find((c) => c.code.toLowerCase() === normalized);
  return byCode ? byCode.code : null;
}
