using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using AzureRestApi.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace AzureRestApi.Repositories
{
    public class AccessTokenRepository
    {
        private readonly Settings _settings;
        private string? _accessToken;

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

        public async Task<string> GetAccessToken()
        {
            if (!string.IsNullOrWhiteSpace(_accessToken)) return _accessToken;

            var keyvaultUri = "https://" + _settings.KeyVaultName + ".vault.azure.net";
            var credential = new DefaultAzureCredential();
            var client = new SecretClient(new Uri(keyvaultUri), credential);
            var clientId = (await client.GetSecretAsync("ClientID")).Value.Value;
            var clientSecret = (await client.GetSecretAsync("ClientSecret")).Value.Value;

            ClientCredential cc = new(clientId, clientSecret);
            var context = new AuthenticationContext("https://login.microsoftonline.com/" + _settings.AzureTenantId);
            var result = context.AcquireTokenAsync("https://management.azure.com/", cc);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the Access token");
            }
            _accessToken = result.Result.AccessToken;

            return _accessToken;
        }
    }
}
