/**
 * Sanitization Middleware
 * Sanitizes string inputs in req.body and req.query to prevent stored XSS.
 * 
 * Uses the unified sanitizeObject utility from @utils/sanitizer.
 * 
 * This middleware runs AFTER body parsing and BEFORE route handlers.
 * File upload routes (multipart) are skipped — those are handled
 * by the malwareScan middleware pipeline (but can be manually sanitized in controllers).
 */

import { Request, Response, NextFunction } from 'express';
import { sanitizeObject, sanitizeStrict } from '@utils/sanitizer';

/**
 * Express middleware that sanitizes req.body and req.query
 * Skips multipart/form-data requests (file uploads handled by malwareScan)
 */
export const sanitizationMiddleware = (req: Request, _res: Response, next: NextFunction): void => {
    try {
        // Skip multipart requests — file uploads are sanitized by the malware scan pipeline
        // Note: Multipart payloads should be manually sanitized in the controller if used.
        const contentType = req.headers['content-type'] || '';
        if (contentType.includes('multipart/form-data')) {
            return next();
        }

        // Sanitize req.body (POST/PUT/PATCH payloads)
        if (req.body && typeof req.body === 'object' && Object.keys(req.body).length > 0) {
            req.body = sanitizeObject(req.body);
        }

        // Sanitize req.query (GET query parameters) — always strict (no HTML in query params)
        if (req.query && typeof req.query === 'object' && Object.keys(req.query).length > 0) {
            const strictQuery: Record<string, any> = {};
            for (const key of Object.keys(req.query)) {
                const val = req.query[key];
                if (typeof val === 'string') {
                    strictQuery[key] = sanitizeStrict(val);
                } else {
                    strictQuery[key] = val;
                }
            }
            req.query = strictQuery as any;
        }

        next();
    } catch (error) {
        // If sanitization fails for any reason, don't block the request —
        // downstream validation (Zod) will catch malformed input
        console.warn('Sanitization middleware warning:', error instanceof Error ? error.message : 'Unknown error');
        next();
    }
};
