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

namespace AzureRestApi.Repositories
{
    public abstract class AzureBaseRepository<T>
    {
        private readonly HttpClient _httpClient;
        private readonly AccessTokenRepository _accessTokenRepository;

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

        protected async Task<List<T>> GetAllByUri(Uri uri)
        {
            var accessToken = await _accessTokenRepository.GetAccessToken();

            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);

            try
            {
                response.EnsureSuccessStatusCode();

                var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var result = JsonSerializer.Deserialize<ApiResponse<T>>(responseString)?.value;
                return result ?? new List<T>();

            }
            catch
            {
                return new List<T>();
            }
        }
    }
}
