<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\Middleware;
use App\Core\Request;

final class RequestTimingMiddleware implements Middleware
{
    public function handle(Request $request, callable $next): mixed
    {
        $started = microtime(true);
        $response = $next();
        $elapsed = round((microtime(true) - $started) * 1000, 2);

        if (filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOL)) {
            header('X-Request-Time: ' . $elapsed . 'ms');
        }

        return $response;
    }
}
