/**
 * Maps Convex addItem (and related) errors to user-facing messages.
 * Used by PDP and product grid add-to-cart flows for consistent error copy (ATC-4).
 *
 * Backend errors (convex/carts.ts addItem):
 * - "Must be authenticated or provide sessionId"
 * - "Quantity must be at least 1"
 * - "Variant not found"
 * - "Variant is not available"
 * - "Insufficient stock: only N available"
 */

/** Exact backend message → user-facing copy */
const EXACT_MAP: Record<string, string> = {
  "Must be authenticated or provide sessionId":
    "Please sign in or refresh the page and try again.",
  "Quantity must be at least 1": "Please choose at least 1 item.",
  "Variant not found": "This variant is no longer available.",
  "Variant is not available": "This variant is no longer available.",
};

const INSUFFICIENT_STOCK_REGEX = /^Insufficient stock: only (\d+) available$/;

const DEFAULT_MESSAGE = "Could not add to cart. Please try again.";

/**
 * Returns a user-facing error message for add-to-cart failures.
 * Call this in .catch() when addItem (or similar) rejects.
 */
export function getAddToCartErrorMessage(err: unknown): string {
  const message =
    err instanceof Error ? err.message : typeof err === "string" ? err : "";
  if (!message) return DEFAULT_MESSAGE;

  const exact = EXACT_MAP[message];
  if (exact) return exact;

  const stockMatch = message.match(INSUFFICIENT_STOCK_REGEX);
  if (stockMatch) {
    const n = stockMatch[1];
    return `Insufficient stock: only ${n} available. Try a lower quantity.`;
  }

  return DEFAULT_MESSAGE;
}
