export interface ExtractedIntentAndFilters {
  intent: "product_search" | "policy_inquiry" | "order_status" | "cart_action" | "general_qa";
  queryText: string;
  maxPrice?: number;
  minPrice?: number;
  categoryFilter?: string;
}

/**
 * Extracts shopping intent and structured search filters (price limits, keywords) from customer queries.
 */
export function extractIntentAndFilters(userMessage: string): ExtractedIntentAndFilters {
  const clean = (userMessage || "").trim();
  const lower = clean.toLowerCase();

  // 1. Intent Detection
  let intent: ExtractedIntentAndFilters["intent"] = "general_qa";
  if (/return|refund|exchange|shipping|delivery|dispatch|warranty|guarantee|policy|faq/i.test(lower)) {
    intent = "policy_inquiry";
  } else if (/order|track|tracking|status|where is my|shipment/i.test(lower)) {
    intent = "order_status";
  } else if (/cart|checkout|buy now|add to cart|purchase/i.test(lower)) {
    intent = "cart_action";
  } else if (/find|show|need|looking for|search|have any|dress|shirt|shoe|boots|coffee|headphone|mug|pant|jacket|bag/i.test(lower)) {
    intent = "product_search";
  }

  // 2. Price filter extraction (e.g. "under $100", "below 50", "under 150USD")
  let maxPrice: number | undefined = undefined;
  const underPriceMatch = lower.match(/(?:under|below|less than|max|up to)\s*[\$€£₹]?\s*(\d+(?:\.\d{1,2})?)/i);
  if (underPriceMatch && underPriceMatch[1]) {
    const p = parseFloat(underPriceMatch[1]);
    if (!isNaN(p) && p > 0) {
      maxPrice = p;
    }
  }

  // 3. Keyword extraction: remove filler words
  let queryText = clean
    .replace(/(?:under|below|less than|max|up to)\s*[\$€£₹]?\s*(\d+(?:\.\d{1,2})?)/gi, "")
    .replace(/\b(i need|i want|show me|do you have|can i see|looking for|please find|what are your|what do you have in)\b/gi, "")
    .replace(/[^\w\s-]/g, " ")
    .replace(/\s+/g, " ")
    .trim();

  return {
    intent,
    queryText,
    maxPrice,
  };
}
