<?php

namespace NoahVet\Reef\Bridge\Reef\IAM\Client;

use NoahVet\Reef\Factory\ClientFactoryInterface;
use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Security\Authentication\Token\ReefOAuthToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class ClientAdapter implements ClientAdapterInterface
{
    /**
     * @psalm-suppress PropertyNotSetInConstructor
     */
    private string $serviceToken;

    public function __construct(
        private readonly TokenStorageInterface $tokenStorage,
        private readonly ClientFactoryInterface $clientFactory,
    ) {
    }

    #[\Override]
    public function getClient(): Client
    {
        return $this->clientFactory->create($this->getToken()->getBearerToken());
    }

    #[\Override]
    public function getServiceClient(): Client
    {
        return $this->clientFactory->create($this->serviceToken);
    }

    #[\Override]
    public function getToken(): ReefOAuthToken
    {
        if (null == $this->serviceToken) {
            throw new \LogicException('The service token should be not null at this step.');
        }

        /** @var ReefOAuthToken|null $token */
        $token = $this->tokenStorage->getToken();

        if (null == $token) {
            throw new \LogicException('The token in token storage should be not null at this step.');
        }

        return $token;
    }

    #[\Override]
    public function setServiceToken(string $serviceToken): self
    {
        $this->serviceToken = $serviceToken;

        return $this;
    }
}
