<?php

namespace Velis\Microsoft;

use Velis\Cache\CacheInterface;
use Velis\Microsoft\TokenProvider;

class TokenService
{
    private TokenProvider $tokenProvider;
    private CacheInterface $cache;

    public function __construct(TokenProvider $tokenProvider, CacheInterface $cache)
    {
        $this->tokenProvider = $tokenProvider;
        $this->cache = $cache;
    }

    public function getToken(string $clientId, string $clientSecret, string $scope): string
    {
        $cacheKey = $this->getCacheKey($clientId, $scope);

        if ($this->cache->has($cacheKey)) {
            /** @var Token $token */
            $token = $this->cache->get($cacheKey);
        }

        if ($token && $token->isExpired()) {
            unset($token);
        }

        if (!isset($token)) {
            $token = $this->tokenProvider->getToken($clientId, $clientSecret, $scope);
            $this->cache->set($cacheKey, $token, $token->getExpiresIn());
        }

        return $token->getAccessToken();
    }

    private function getCacheKey(string $clientId, string $scope): string
    {
        return 'ms_token' . sha1($clientId . $scope);
    }
}
