const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');

// Security headers middleware
const securityHeaders = helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["'self'"],
            styleSrc: ["'self'", "'unsafe-inline'"],
            scriptSrc: ["'self'"],
            imgSrc: ["'self'", "data:", "https:"],
        },
    },
    hsts: {
        maxAge: 31536000,
        includeSubDomains: true,
        preload: true
    }
});

// Request sanitization middleware
const sanitizeInput = [
    // MongoDB injection prevention
    (req, res, next) => {
        mongoSanitize();
        next();
    },
    
    // XSS protection
    (req, res, next) => {
        xss();
        next();
    },
    
    // Additional sanitization for string fields
    (req, res, next) => {
        if (req.body) {
            const stringFields = ['name', 'mobile', 'fullName', 'nativePlace'];
            stringFields.forEach(field => {
                if (req.body[field] && typeof req.body[field] === 'string') {
                    req.body[field] = req.body[field]
                        .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') // Remove script tags
                        .replace(/javascript:/gi, '') // Remove javascript: protocol
                        .trim();
                }
            });
        }
        next();
    }
];

// Password strength validation middleware
const validatePasswordStrength = (req, res, next) => {
    if (req.body.password) {
        const password = req.body.password;
        
        // Check for common weak passwords
        const commonPasswords = [
            'password', '123456', '123456789', 'qwerty', 'abc123',
            'password123', 'admin', 'letmein', 'welcome', 'monkey'
        ];
        
        if (commonPasswords.includes(password.toLowerCase())) {
            return res.status(400).json({
                success: false,
                message: 'Password is too common, please choose a stronger password'
            });
        }
        
        // Check for sequential characters
        const hasSequential = /(.)\1{2,}/.test(password);
       
    }
    
    next();
};

// Request size limiter
const requestSizeLimiter = (req, res, next) => {
    const contentLength = parseInt(req.get('content-length') || '0');
    const maxSize = 1024 * 1024; // 1MB
    
    if (contentLength > maxSize) {
        return res.status(413).json({
            success: false,
            message: 'Request entity too large'
        });
    }
    
    next();
};

// IP whitelist middleware (optional - for production)
const ipWhitelist = (allowedIPs = []) => {
    return (req, res, next) => {
        // Skip if no IPs are configured (development mode)
        if (allowedIPs.length === 0) {
            return next();
        }
        
        const clientIP = req.ip || req.connection.remoteAddress;
        
        if (!allowedIPs.includes(clientIP)) {
            return res.status(403).json({
                success: false,
                message: 'Access denied from this IP address'
            });
        }
        
        next();
    };
};

module.exports = {
    securityHeaders,
    sanitizeInput,
    validatePasswordStrength,
    requestSizeLimiter,
    ipWhitelist
};
