<?php

namespace NoahVet\Reef\Factory;

use NoahVet\Reef\Plugin\Cache\HttpCachePlugin;
use NoahVet\Reef\Plugin\Cache\HttpResponseCacheInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;

class Psr18HttpClientFactory implements HttpClientFactoryInterface
{
    public function __construct(
        private readonly HttpResponseCacheInterface $httpResponseCache,
    ) {
    }

    #[\Override]
    public function create(bool $withCache = true): ClientInterface
    {
        $plugins = [];
        if ($withCache) {
            $plugins[] = new HttpCachePlugin($this->httpResponseCache);
        }
        $httpClient = \Http\Discovery\Psr18ClientDiscovery::find();

        return new \Http\Client\Common\PluginClient($httpClient, $plugins);
    }

    #[\Override]
    public function getRequestFactory(): RequestFactoryInterface
    {
        return \Http\Discovery\Psr17FactoryDiscovery::findRequestFactory();
    }

    #[\Override]
    public function getStreamFactory(): StreamFactoryInterface
    {
        return \Http\Discovery\Psr17FactoryDiscovery::findStreamFactory();
    }
}
