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

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

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

        internal async Task<List<UserResponse>> GetAll(List<string> ids)
        {
            var authorizationToken = await _accessTokenRepository.GetAuthorizationToken();
            List<UserResponse> result = new();
            UserResponse? responseItem;

            foreach (var id in ids)
            {
                HttpRequestMessage request = new(HttpMethod.Get, $"{_settings.SnykBaseUrl}user/{id}");
                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);

                try
                {
                    response.EnsureSuccessStatusCode();

                    var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    responseItem = JsonSerializer.Deserialize<UserResponse>(responseString);

                    if (responseItem != null)
                    {
                        result.Add(responseItem);
                    }
                }
                catch
                {
                    AnsiConsole.MarkupLine($"[red bold]Could not find user with id '{id}'[/]");
                    result.Add(new()
                    {
                        Id = id,
                        Name = "{ Unknown user }",
                        UserName = "{ Unknown user }",
                        Email = "{ Unknown user }"
                    });
                }
            }

            return result;
        }
    }
}
