<?php

/**
 * Chill is a software for social workers.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;

use Symfony\Component\HttpFoundation\Session\SessionInterface;
use TheNetworg\OAuth2\Client\Provider\Azure;
use TheNetworg\OAuth2\Client\Token\AccessToken;

/**
 * Store token obtained on behalf of a User.
 */
class OnBehalfOfUserTokenStorage
{
    final public const MS_GRAPH_ACCESS_TOKEN = 'msgraph_access_token';

    public function __construct(private readonly Azure $azure, private readonly SessionInterface $session) {}

    public function getToken(): AccessToken
    {
        /** @var ?AccessToken $token */
        $token = $this->session->get(self::MS_GRAPH_ACCESS_TOKEN, null);

        if (null === $token) {
            throw new \LogicException('unexisting token');
        }

        if ($token->hasExpired()) {
            $token = $this->azure->getAccessToken('refresh_token', [
                'refresh_token' => $token->getRefreshToken(),
            ]);

            $this->setToken($token);
        }

        return $token;
    }

    public function hasToken(): bool
    {
        return $this->session->has(self::MS_GRAPH_ACCESS_TOKEN);
    }

    public function setToken(AccessToken $token): void
    {
        $this->session->set(self::MS_GRAPH_ACCESS_TOKEN, $token);
    }
}
