using AzureRestApi.Models.Api;
using AzureRestApi.Models.Resources;
using System.Net.Http.Headers;
using System.Text.Json;

namespace AzureRestApi.Repositories
{
    public class AzureSubscriptionRepository
    {
        private readonly HttpClient _httpClient;
        private readonly AccessTokenRepository _accessTokenRepository;

        public AzureSubscriptionRepository(HttpClient httpClient, AccessTokenRepository accessTokenRepository)
        {
            _httpClient = httpClient;
            _accessTokenRepository = accessTokenRepository;
        }

        public async Task<List<Subscription>?> GetAll()
        {
            // GET https://management.azure.com/subscriptions?api-version=2020-01-01

            var accessToken = await _accessTokenRepository.GetAccessToken();
            var uri = new Uri("https://management.azure.com/subscriptions?api-version=2020-01-01");

            HttpRequestMessage request = new(HttpMethod.Get, uri);
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();

            var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            
            return JsonSerializer.Deserialize< ApiResponse<Subscription>>(responseString)?.value;
        }
    }
}
