<?php

declare(strict_types=1);

namespace NoahVet\Reef\Factory;

use Jane\Component\OpenApiRuntime\Client\Plugin\AuthenticationRegistry;
use NoahVet\Reef\Jane\Authentication\BearerAuthAuthentication;
use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Plugin\Cache\HttpCachePlugin;
use NoahVet\Reef\Plugin\Cache\HttpResponseCacheInterface;
use NoahVet\Reef\Plugin\ConfigureUrlPlugin;

class ClientFactory implements ClientFactoryInterface
{
    protected string $url;

    public function __construct(
        string $reefUrl,
        private readonly HttpResponseCacheInterface $httpResponseCache,
    ) {
        $this->url = $reefUrl;
    }

    public function create(string $bearerToken): Client
    {
        return self::createClient($bearerToken, Client::class);
    }

    /**
     * @template TClient of object
     *
     * @param class-string<TClient> $clientClass
     *
     * @return TClient
     */
    public function createClient(string $bearerToken, string $clientClass): object
    {
        if (!\method_exists($clientClass, 'create')) {
            throw new \RuntimeException('The client class has no create method');
        }

        $authPlugins = [new BearerAuthAuthentication($bearerToken)];

        return $clientClass::create(
            null,
            [
                new AuthenticationRegistry($authPlugins),
                new ConfigureUrlPlugin($this->url),
                new HttpCachePlugin($this->httpResponseCache),
            ],
        );
    }
}
