<?php

declare(strict_types=1);

namespace App\Framework\HttpClient;

final class HttpClientWithMiddleware implements HttpClient
{
    /** @var HttpClientMiddleware[] */
    private array $middlewares = [];

    public function __construct(
        private readonly HttpClient $client
    ) {
    }

    /**
     * Fügt Middleware hinzu
     */
    public function addMiddleware(HttpClientMiddleware $middleware): self
    {
        $this->middlewares[] = $middleware;

        return $this;
    }

    /**
     * Führt Request mit Middleware-Chain aus
     */
    public function send(ClientRequest $request): ClientResponse
    {
        $handler = $this->buildHandler();

        return $handler($request);
    }

    private function buildHandler(): callable
    {
        $handler = fn (ClientRequest $request) => $this->client->send($request);

        // Middleware in umgekehrter Reihenfolge anwenden
        foreach (array_reverse($this->middlewares) as $middleware) {
            $handler = fn (ClientRequest $request) => $middleware($request, $handler);
        }

        return $handler;
    }
}
