import { PaymentMethod, PaymentMethodSchema } from "../schema/receipt";

const KEYWORD_MAP: Array<{ pattern: RegExp; value: PaymentMethod }> = [
  { pattern: /\bapple[\s_-]?pay\b/i, value: "APPLE_PAY" },
  { pattern: /\bgoogle[\s_-]?pay\b|\bgpay\b/i, value: "GOOGLE_PAY" },
  { pattern: /\bpaypal\b/i, value: "PAYPAL" },
  {
    pattern: /\b(visa|mastercard|amex|american[\s_-]?express|kreditkarte|credit[\s_-]?card)\b/i,
    value: "KREDITKARTE",
  },
  {
    pattern: /\b(ec[\s_-]?karte|girocard|giro[\s_-]?card|maestro|debit|bankkarte|electronic[\s_-]?cash)\b/i,
    value: "EC_KARTE",
  },
  {
    pattern: /überweisung|ueberweisung|\bsepa\b|bank[\s_-]?transfer|\bwire\b/i,
    value: "UEBERWEISUNG",
  },
  { pattern: /\b(bar|cash|bargeld)\b/i, value: "BAR" },
];

/**
 * Map model output / printed labels onto the payment-method enum.
 * Unknown non-empty values become SONSTIGE; empty stays null.
 */
export function normalizePaymentMethod(raw: unknown): PaymentMethod | null {
  if (raw === null || raw === undefined) return null;
  if (typeof raw !== "string") return null;
  const trimmed = raw.trim();
  if (!trimmed) return null;

  const asEnum = PaymentMethodSchema.safeParse(trimmed.toUpperCase().replace(/[\s-]+/g, "_"));
  if (asEnum.success) return asEnum.data;

  for (const { pattern, value } of KEYWORD_MAP) {
    if (pattern.test(trimmed)) return value;
  }
  return "SONSTIGE";
}
