const NUMERIC_FIELDS = ['purchasePrice', 'sellingPrice', 'lowStockThreshold', 'currentStock', 'measurementValue'];

const parseJsonField = (value) => {
  try {
    return JSON.parse(value);
  } catch {
    return null;
  }
};

export const parseFormDataFields = (req, res, next) => {
  if (req.body.sizeVariants && typeof req.body.sizeVariants === 'string') {
    const parsed = parseJsonField(req.body.sizeVariants);
    if (parsed) req.body.sizeVariants = parsed;
  }
  if (req.body.variants && typeof req.body.variants === 'string') {
    const parsed = parseJsonField(req.body.variants);
    if (parsed) req.body.variants = parsed;
  }
  if (req.body.discountRules && typeof req.body.discountRules === 'string') {
    const parsed = parseJsonField(req.body.discountRules);
    if (parsed) req.body.discountRules = parsed;
  }
  NUMERIC_FIELDS.forEach((field) => {
    if (req.body[field] !== undefined && typeof req.body[field] === 'string') {
      const num = Number(req.body[field]);
      if (!isNaN(num)) req.body[field] = num;
    }
  });
  next();
};