using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.API.Settings;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика RabbitMQ
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatRabbitMqController : BaseApiController
    {
        private readonly IRabbitService mqService;
        private readonly MqSettings mqSettings;
        private readonly ILogger<StatRabbitMqController> logger;
        private readonly IRabbitAdminService mqAdminService;
        private readonly MonitoringSettings monitoringSettings;

        public StatRabbitMqController(
            IRabbitService mqService,
            MqSettings mqSettings,
            ILogger<StatRabbitMqController> logger,
            IRabbitAdminService mqAdminService,
            MonitoringSettings monitoringSettings
            )
        {
            this.mqService = mqService;
            this.mqSettings = mqSettings;
            this.logger = logger;
            this.mqAdminService = mqAdminService;
            this.monitoringSettings = monitoringSettings;
        }

        /// <summary>
        /// Статистика очередей в RabbitMQ
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatRabbitMq.GetQueueStats)]
        public async Task<IActionResult> GetQueueStats()
        {
            var result = await mqAdminService.GetQueuesAsync(mqSettings.Statistics.StatMqAuth);

            if (!result.IsSuccess)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при получении статистики из RabbitMQ." } }));

            return Ok(new Response<object?>(result.Response, true));

            #region comments
            //var response = new List<StatRabbitMqQueueResponse>();

            //// список очередей
            //foreach (var queue in mqSettings.Statistics.QueueList)
            //{
            //    var result = mqService.GetQueueCount(mqSettings.Statistics.StatMqAuth, queue);

            //    if (!result.IsSuccess)
            //    {
            //        logger.LogError(result.Exception, $"Ошибка при запросе статистики из RabbitMQ для очереди: ${queue}");
            //        return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"" } }));
            //    }

            //    response.Add(new StatRabbitMqQueueResponse { Name = queue, Consumers = result.ConsumerCount, MessagesTotal = result.Count });
            //}

            //return Ok(new Response<List<StatRabbitMqQueueResponse>>(response.OrderBy(t => t.Name).ToList(), true));
            #endregion
        }


        /// <summary>
        /// Статистика соединений в RabbitMQ
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatRabbitMq.GetConnectionStats)]
        public async Task<IActionResult> GetConnectionStats()
        {
            var result = await mqAdminService.GetConnectionsAsync(mqSettings.Statistics.StatMqAuth);

            if (!result.IsSuccess)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при получении статистики из RabbitMQ." } }));

            var response = new StatRabbitMqConnectionsResponse
            {
                MqData = result.Response,
                MonitoringSettings = new StatRabbitMqConnectionsMonitoringSettings
                {
                    ThresholdConnections = monitoringSettings.RabbitMq?.ThresholdConnections ?? 0
                }
            };

            return Ok(new Response<StatRabbitMqConnectionsResponse>(response, true));
        }
    }
}
