<?php

declare(strict_types=1);

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
     */
    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));
    }
}
