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

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

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

        internal async Task<List<AuditLogResponse>> GetByOrganizationId(string origanizationId)
        {
            var authorizationToken = await _accessTokenRepository.GetAuthorizationToken();
            List<AuditLogResponse> result = new();
            List<AuditLogResponse> responseItems;

            int page = 0;

            do
            {
                HttpRequestMessage request = new(HttpMethod.Post, $"{_settings.SnykBaseUrl}org/{origanizationId}/audit?from=2022-07-01&page={++page}");
                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);
                responseItems = JsonSerializer.Deserialize<List<AuditLogResponse>>(responseString) ?? new List<AuditLogResponse>();
                result.AddRange(responseItems);
            }
            while (responseItems.Count == 100);

            return result;
        }
    }
}
