<?php

declare(strict_types=1);

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,
    ) {
    }

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

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

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