<?php

namespace App\Middlewares;

use App\Core\Request;
use App\Core\Response;

class SecurityMiddleware
{
    /**
     * Applies OWASP security headers and sanitizes incoming body/query parameters
     * to protect against XSS and basic Injection.
     */
    public function handle(Request $request, Response $response): void
    {
        // 1. Set OWASP Security Headers
        $response->setHeader('X-Frame-Options', 'DENY'); // Prevent Clickjacking
        $response->setHeader('X-XSS-Protection', '1; mode=block'); // Prevent Cross-Site Scripting (XSS)
        $response->setHeader('X-Content-Type-Options', 'nosniff'); // Prevent MIME-sniffing
        $response->setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload'); // HSTS
        $response->setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; object-src 'none';"); // CSP

        // 2. Input Sanitization to prevent XSS (Recursive)
        $body = $request->getBody();
        if (is_array($body)) {
            $request->setBody($this->sanitizeArray($body));
        }

        $query = $request->getQueryParams();
        if (is_array($query)) {
            $request->setQueryParams($this->sanitizeArray($query));
        }
    }

    /**
     * Recursively trim input arrays
     */
    private function sanitizeArray(array $data): array
    {
        $sanitized = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $sanitized[$key] = $this->sanitizeArray($value);
            } elseif (is_string($value)) {
                $sanitized[$key] = trim($value);
            } else {
                $sanitized[$key] = $value;
            }
        }
        return $sanitized;
    }
}
