/**
 * Price field cleaning and formatting utilities
 */

/**
 * Cleans a price field by removing currency symbols and formatting to 2 decimal places
 *
 * - Removes dollar signs ($) and commas (,)
 * - Converts to number and formats with 2 decimal places
 * - Returns original value if conversion fails
 *
 * @param value - Price value to clean (string or number)
 * @returns Cleaned price string formatted to 2 decimals, or original value if invalid
 *
 * @example
 * cleanPriceField("$1,234.56") // "1234.56"
 * cleanPriceField("$99.9") // "99.90"
 * cleanPriceField(123.456) // "123.46"
 * cleanPriceField("invalid") // "invalid"
 */
export function cleanPriceField(value: string | number): string {
  if (typeof value === "string") {
    const cleaned = value.replace(/[$,]/g, "");
    const numValue = parseFloat(cleaned);
    if (!isNaN(numValue)) {
      return numValue.toFixed(2);
    }
    return value;
  }

  if (typeof value === "number") {
    return value.toFixed(2);
  }

  return String(value);
}

/**
 * Cleans multiple price fields in a data object
 *
 * @param data - Object containing price fields
 * @param priceFields - Array of field keys to clean
 * @returns New object with cleaned price fields
 *
 * @example
 * cleanPriceFields({ msrp: "$99.99", cost_each: "$50.00" }, ["msrp", "cost_each"])
 * // { msrp: "99.99", cost_each: "50.00" }
 */
export function cleanPriceFields<T extends Record<string, any>>(
  data: T,
  priceFields: (keyof T)[]
): T {
  const cleaned = { ...data };

  for (const field of priceFields) {
    if (cleaned[field] !== undefined && cleaned[field] !== null) {
      cleaned[field] = cleanPriceField(cleaned[field]) as any;
    }
  }

  return cleaned;
}