<?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 Chill\MainBundle\Redis\ChillRedis;
use League\OAuth2\Client\Token\AccessTokenInterface;
use TheNetworg\OAuth2\Client\Provider\Azure;
use TheNetworg\OAuth2\Client\Token\AccessToken;

class MachineTokenStorage
{
    private const KEY = 'msgraph_access_token';

    private ?AccessTokenInterface $accessToken = null;

    public function __construct(private readonly Azure $azure, private readonly ChillRedis $chillRedis) {}

    public function getToken(): AccessTokenInterface
    {
        if (null === $this->accessToken || $this->accessToken->hasExpired()) {
            $this->accessToken = $this->azure->getAccessToken('client_credentials', [
                'scope' => 'https://graph.microsoft.com/.default',
            ]);
        }

        return $this->accessToken;
    }

    public function storeToken(AccessToken $token): void
    {
        $this->chillRedis->set(self::KEY, serialize($token));
    }
}
