<?php

declare(strict_types=1);

namespace App\Framework\HttpClient\Middleware;

use App\Framework\Core\ValueObjects\Duration;
use App\Framework\DateTime\Timer;
use App\Framework\HttpClient\ClientRequest;
use App\Framework\HttpClient\ClientResponse;
use App\Framework\HttpClient\HttpClientMiddleware;

final class RateLimitingMiddleware implements HttpClientMiddleware
{
    private array $lastRequestTimes = [];

    public function __construct(
        private readonly Timer $timer,
        private readonly int $maxRequests = 10,
        private readonly int $windowSeconds = 60
    ) {
    }

    public function __invoke(ClientRequest $request, callable $next): ClientResponse
    {
        $host = parse_url($request->url, PHP_URL_HOST);
        $now = time();

        if (! isset($this->lastRequestTimes[$host])) {
            $this->lastRequestTimes[$host] = [];
        }

        // Alte Requests aus dem Window entfernen
        $this->lastRequestTimes[$host] = array_filter(
            $this->lastRequestTimes[$host],
            fn ($time) => $now - $time < $this->windowSeconds
        );

        // Rate-Limit prüfen
        if (count($this->lastRequestTimes[$host]) >= $this->maxRequests) {
            $oldestRequest = min($this->lastRequestTimes[$host]);
            $waitTime = $this->windowSeconds - ($now - $oldestRequest);

            if ($waitTime > 0) {
                $this->timer->sleep(Duration::fromSeconds($waitTime));
            }
        }

        // Request-Zeit erfassen
        $this->lastRequestTimes[$host][] = $now;

        return $next($request);
    }
}
