using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using SnykRestApi.Models;

namespace SnykRestApi.Repositories
{
    public class AccessTokenRepository
    {
        private readonly Settings _settings;
        private string? _authorizationToken = string.Empty;

        public AccessTokenRepository(Settings settings)
        {
            _settings = settings;
        }

        public async Task<string> GetAuthorizationToken()
        {
            if (!string.IsNullOrWhiteSpace(_authorizationToken)) return _authorizationToken;

            var keyvaultUri = "https://" + _settings.KeyVaultName + ".vault.azure.net";
            var credential = new DefaultAzureCredential();
            var client = new SecretClient(new Uri(keyvaultUri), credential);
            _authorizationToken = (await client.GetSecretAsync("SnykKey")).Value.Value;
            
            return _authorizationToken;
        }
    }
}
