const CONTROL_CHARACTERS_PATTERN = /[\u0000-\u001F\u007F]/g;

const sanitizeString = (value) =>
  value
    .replace(CONTROL_CHARACTERS_PATTERN, "")
    .replace(/[<>]/g, "")
    .replace(/\s+/g, " ")
    .trim();

export const sanitizeValue = (value) => {
  if (Array.isArray(value)) {
    return value.map((item) => sanitizeValue(item));
  }

  if (value && typeof value === "object" && value.constructor === Object) {
    return Object.entries(value).reduce((accumulator, [key, item]) => {
      accumulator[key] = sanitizeValue(item);
      return accumulator;
    }, {});
  }

  if (typeof value === "string") {
    return sanitizeString(value);
  }

  return value;
};

export const sanitizeRequest = (req, res, next) => {
  req.body = sanitizeValue(req.body);
  req.query = sanitizeValue(req.query);
  req.params = sanitizeValue(req.params);
  next();
};
