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

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

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

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

            var uri = $"{_settings.SnykBaseUrl}org/{organizationId}/projects";
            HttpRequestMessage request = new(HttpMethod.Post, 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<ProjectListResponse>(responseString)?.Projects;
            return result ?? new List<ProjectResponse>();
        }
    }
}
