using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Domain.DTOs.RabbitApi;
using PARR.Domain.Settings;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace PARR.Infrastructure.Rabbit
{
    internal class RabbitAdminService : IRabbitAdminService
    {
        private readonly HttpClient httpClient;
        private readonly ILogger<RabbitAdminService> logger;

        public RabbitAdminService(HttpClient httpClient, ILogger<RabbitAdminService> logger)
        {
            this.httpClient = httpClient;
            this.logger = logger;
        }


        public async Task<RabbitApiResult> GetConnectionsAsync(IMqSettings mqSettings)
        {
            var url = $"http://{mqSettings.HostName}:15672/api/connections";

            return await SendRequestAsync(mqSettings, url);
        }


        public async Task<RabbitApiResult> GetQueuesAsync(IMqSettings mqSettings)
        {
            var url = $"http://{mqSettings.HostName}:15672/api/queues";

            return await SendRequestAsync(mqSettings, url);
        }


        private async Task<RabbitApiResult> SendRequestAsync(IMqSettings mqSettings, string url)
        {
            SetAuthorizationHeaders(mqSettings);

            try
            {
                var result = await httpClient.GetAsync(url);

                if (result.StatusCode == HttpStatusCode.OK)
                {
                    var content = await result.Content.ReadAsStringAsync();
                    var json = JsonSerializer.Deserialize<object>(content);

                    return new RabbitApiResult { IsSuccess = true, Response = json };
                }
                else
                {
                    logger.LogError($"Ошибка при запросе к RabbitMq, url: {url}, StatusCode: {result.StatusCode}");

                    return new RabbitApiResult { IsSuccess = false };
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"Ошибка при запросе к RabbitMQ, url: {url}");
                return new RabbitApiResult { IsSuccess = false, Exception = ex };
            }
        }


        private void SetAuthorizationHeaders(IMqSettings mqSettings)
        {
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{mqSettings.User}:{mqSettings.Password}")));

        }
    }
}
