<?php

namespace Licenzo\Http\Middleware;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Http\Request;
use Licenzo\Framework\Http\Response;

class OptimizeResponse
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);

        // Add performance headers
        if ($response instanceof Response) {
            $this->addPerformanceHeaders($response);
            $this->optimizeResponse($response, $request);
        }

        return $response;
    }

    /**
     * Add performance-related headers.
     */
    protected function addPerformanceHeaders(Response $response): void
    {
        // Add cache control headers for API responses
        $response->header('Cache-Control', 'no-cache, must-revalidate, max-age=0');
        $response->header('X-Content-Type-Options', 'nosniff');
        $response->header('X-Frame-Options', 'DENY');
        $response->header('X-XSS-Protection', '1; mode=block');
    }

    /**
     * Optimize response based on request.
     */
    protected function optimizeResponse(Response $response, Request $request): void
    {
        // Add request timing if in debug mode
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $response->header('X-Debug-Time', microtime(true) - $request->get('REQUEST_TIME_FLOAT'));
            $response->header('X-Debug-Memory', memory_get_peak_usage(true));
        }
    }
}
