// src/utils/priceParser.ts
/**
 * Parses a price string into an integer number of cents.
 * Handles formats like "$10.99", "99¢", "250", and ".99".
 * @param price The price string to parse.
 * @returns The price in cents, or null if unparsable.
 */
export const parsePriceToCents = (price: string): number | null => {
  if (!price || typeof price !== 'string') return null;

  const cleanedPrice = price.trim();

  // Handle "X for Y" cases - these are not a single item price.
  if (cleanedPrice.match(/\d+\s+for/i)) {
    return null;
  }

  // Handle "99¢" format.
  const centsMatch = cleanedPrice.match(/^(\d+\.?\d*)\s?¢$/);
  if (centsMatch && centsMatch[1]) {
    return Math.round(parseFloat(centsMatch[1]));
  }

  // Handle "$10.99", "10.99", or ".99" format.
  const dollarsMatch = cleanedPrice.match(/^\$?((?:\d{1,3}(?:,\d{3})*|\d+))?(\.\d+)?$/);

  // Check if either the dollar part (group 1) OR decimal part (group 2) exists.
  // This allows strings like ".99" where group 1 is empty but group 2 is matched.
  if (dollarsMatch && (dollarsMatch[1] !== undefined || dollarsMatch[2] !== undefined)) {
    // Remove commas and dollar signs before parsing.
    const numericString = dollarsMatch[0].replace(/,|\$/g, '');
    const numericValue = parseFloat(numericString);

    // This is a defensive check. The regex is designed to prevent this from ever being NaN.
    // istanbul ignore next
    if (isNaN(numericValue)) return null;

    return Math.round(numericValue * 100);
  }

  return null;
};
