import { Request, Response, NextFunction } from 'express';

const sanitizeValue = (val: any): any => {
  if (typeof val === 'string') {
    // Strip dangerous HTML tags and script injections
    return val
      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
      .replace(/javascript:/gi, '')
      .replace(/onload=/gi, '')
      .replace(/onerror=/gi, '');
  }
  if (typeof val === 'object' && val !== null) {
    for (const key in val) {
      val[key] = sanitizeValue(val[key]);
    }
  }
  return val;
};

export const xssSanitizer = (req: Request, res: Response, next: NextFunction) => {
  if (req.body) req.body = sanitizeValue(req.body);
  if (req.query) req.query = sanitizeValue(req.query);
  if (req.params) req.params = sanitizeValue(req.params);
  next();
};
