<?php

namespace NoahVet\Reef\Plugin\Cache;

use Http\Client\Common\Plugin;
use Http\Promise\FulfilledPromise;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;

class HttpCachePlugin implements Plugin
{
    public function __construct(
        private readonly HttpResponseCacheInterface $httpResponseCache,
    ) {
    }

    /**
     * @param callable(RequestInterface): Promise $next
     * @param callable(RequestInterface): Promise $first
     *
     * @psalm-suppress MoreSpecificImplementedParamType
     */
    #[\Override]
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
    {
        $cachedResponses = $this->httpResponseCache->getCachedResponse($request);
        if (null !== $cachedResponses) {
            $cachedResponses->getBody()->rewind();

            return new FulfilledPromise($cachedResponses);
        }

        return $this->httpResponseCache->cacheResponsePromise($request, $next($request));
    }
}
