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

/**
 * Validation Middleware
 * Handles request validation and sanitization
 */

export const validateUser = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  const { name, email } = req.body;

  // Basic validation
  if (!email || !email.includes('@')) {
    res.status(400).json({ error: 'Valid email is required' });
    return;
  }

  if (name && name.length < 2) {
    res.status(400).json({ error: 'Name must be at least 2 characters long' });
    return;
  }

  next();
};

export const validatePost = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  const { title, authorId } = req.body;

  // Basic validation
  if (!title || title.trim().length === 0) {
    res.status(400).json({ error: 'Title is required' });
    return;
  }

  if (
    authorId &&
    (!Number.isInteger(Number(authorId)) || Number(authorId) <= 0)
  ) {
    res.status(400).json({ error: 'Valid author ID is required' });
    return;
  }

  next();
};

export const sanitizeInput = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  // Basic input sanitization
  const sanitizeString = (str: string): string =>
    str
      .trim()
      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');

  if (req.body) {
    Object.keys(req.body).forEach((key) => {
      if (typeof req.body[key] === 'string') {
        req.body[key] = sanitizeString(req.body[key]);
      }
    });
  }

  next();
};
