import { applyPriceDiscount } from '../pricing';
import { config } from '../config';

const PRICE_FIELD =
  /^(price|final_?price|regular_?price|row_?total|subtotal|grand_?total|amount|value|unit_?price)$/i;

/** Discount numeric price fields in Magento checkoutcart AJAX JSON. */
function patchPriceObject(obj: Record<string, unknown>, depth: number): void {
  if (depth > 8 || !obj || typeof obj !== 'object') return;
  for (const [key, value] of Object.entries(obj)) {
    if (typeof value === 'number' && value >= 0.5 && PRICE_FIELD.test(key)) {
      obj[key] = applyPriceDiscount(value);
      continue;
    }
    if (Array.isArray(value)) {
      for (const item of value) {
        if (item && typeof item === 'object') {
          patchPriceObject(item as Record<string, unknown>, depth + 1);
        }
      }
      continue;
    }
    if (value && typeof value === 'object') {
      patchPriceObject(value as Record<string, unknown>, depth + 1);
    }
  }
}

export function maybePatchCheckoutcartJsonBody(subPath: string, body: Buffer): Buffer {
  const pct = config.pricing.discountPercent;
  if (pct <= 0 || pct >= 100) return body;
  if (!subPath.startsWith('checkoutcart/')) return body;

  const text = body.toString('utf8').trim();
  if (!text.startsWith('{') && !text.startsWith('[')) return body;

  try {
    const data = JSON.parse(text) as Record<string, unknown>;
    patchPriceObject(data, 0);
    return Buffer.from(JSON.stringify(data), 'utf8');
  } catch {
    return body;
  }
}
