import aliasConfig from "@/data/brand-product-aliases.json";

type CanonicalBrand = (typeof aliasConfig.canonicalBrands)[number];
type AliasConfig = {
  canonicalBrands: readonly CanonicalBrand[];
  aliases: Record<CanonicalBrand, readonly string[]>;
};

const typedAliasConfig = aliasConfig as AliasConfig;

function normalizeText(value: string) {
  return value
    .trim()
    .toUpperCase()
    .replace(/[^A-Z0-9]+/g, " ")
    .replace(/\s+/g, " ");
}

export function normalizeImportedBrandValue(value: string) {
  const normalized = normalizeText(value);
  if (!normalized) return null;

  const canonical = typedAliasConfig.canonicalBrands.find((brand) => normalizeText(brand) === normalized);
  if (canonical) {
    return canonical;
  }

  for (const brand of typedAliasConfig.canonicalBrands) {
    const aliases = typedAliasConfig.aliases[brand] ?? [];
    if (aliases.some((alias) => normalized.includes(normalizeText(alias)))) {
      return brand;
    }
  }

  return null;
}
