<?php

namespace NoahVet\Reef\Factory;

use Http\Client\Common\Plugin\HeaderDefaultsPlugin;
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;

    protected string $locale = 'fr_FR';

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

    public function setLocale(string $locale): self
    {
        $this->locale = $locale;

        return $this;
    }

    public function getLocale(): string
    {
        return $this->locale;
    }

    #[\Override]
    public function create(string $bearerToken): Client
    {
        return self::createClient($bearerToken, Client::class);
    }

    /**
     * @template TClient of object
     *
     * @param class-string<TClient> $clientClass
     *
     * @return TClient
     */
    #[\Override]
    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),
                new HeaderDefaultsPlugin(['accept-language' => $this->locale]),
            ],
        );
    }
}
