using SnykRestApi.Models;
using SnykRestApi.Models.Raw;
using System.Net.Http.Headers;
using System.Text.Json;

namespace SnykRestApi.Repositories
{
    public class OrganizationRepository
    {
        private readonly HttpClient _httpClient;
        private readonly AccessTokenRepository _accessTokenRepository;
        private readonly Settings _settings;

        public OrganizationRepository(HttpClient httpClient, AccessTokenRepository accessTokenRepository, Settings settings)
        {
            _httpClient = httpClient;
            _accessTokenRepository = accessTokenRepository;
            _settings = settings;
        }

        internal async Task<List<OrganizationResponse>> GetAll()
        {
            var authorizationToken = await _accessTokenRepository.GetAuthorizationToken();

            var uri = $"{_settings.SnykBaseUrl}orgs";
            HttpRequestMessage request = new(HttpMethod.Get, uri);
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Authorization = new AuthenticationHeaderValue("token", authorizationToken);

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

            response.EnsureSuccessStatusCode();

            var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            var result = JsonSerializer.Deserialize<OrganizationListResponse>(responseString)?.Orgs;
            return result ?? new List<OrganizationResponse>();
        }
    }
}
