<?php

namespace NoahVet\Reef\Plugin\Cache\Promise;

use Http\Client\Common\Deferred;
use Http\Promise\Promise;
use NoahVet\Reef\Plugin\Cache\HttpResponseCacheInterface;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;

class CacheDeferredBuilder
{
    protected Deferred $deferred;

    public function __construct(
        protected readonly Promise $promise,
        protected readonly RequestInterface $request,
        protected readonly HttpResponseCacheInterface $httpResponseCache,
    ) {
        $this->deferred = new Deferred(fn () => $this->waitPromise());
    }

    public function getDeferred(): Deferred
    {
        return $this->deferred;
    }

    protected function waitPromise(): void
    {
        try {
            $this->deferred->resolve($this->httpResponseCache->cacheResponse($this->request, $this->promise->wait()));
        } catch (ClientExceptionInterface $e) {
            $this->deferred->reject($e);
        }
    }
}
