<?php

declare(strict_types=1);

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
{
    private Deferred $deferred;

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

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

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