<?php

declare (strict_types=1);
namespace GDAVSCOPE\Amp\Http\Client\Interceptor;

use GDAVSCOPE\Amp\Cancellation;
use GDAVSCOPE\Amp\ForbidCloning;
use GDAVSCOPE\Amp\ForbidSerialization;
use GDAVSCOPE\Amp\Http\Client\ApplicationInterceptor;
use GDAVSCOPE\Amp\Http\Client\Connection\Stream;
use GDAVSCOPE\Amp\Http\Client\DelegateHttpClient;
use GDAVSCOPE\Amp\Http\Client\NetworkInterceptor;
use GDAVSCOPE\Amp\Http\Client\Request;
use GDAVSCOPE\Amp\Http\Client\Response;
class ModifyRequest implements NetworkInterceptor, ApplicationInterceptor
{
    use ForbidCloning;
    use ForbidSerialization;
    /**
     * @param \Closure(Request):(Request|null) $mapper
     */
    public function __construct(private readonly \Closure $mapper)
    {
    }
    final public function requestViaNetwork(Request $request, Cancellation $cancellation, Stream $stream): Response
    {
        $mappedRequest = ($this->mapper)($request);
        \assert($mappedRequest instanceof Request || $mappedRequest === null);
        return $stream->request($mappedRequest ?? $request, $cancellation);
    }
    public function request(Request $request, Cancellation $cancellation, DelegateHttpClient $httpClient): Response
    {
        $mappedRequest = ($this->mapper)($request);
        \assert($mappedRequest instanceof Request || $mappedRequest === null);
        return $httpClient->request($mappedRequest ?? $request, $cancellation);
    }
}
