using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Enums;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Распределитель РР
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class DistributorController : BaseApiController
    {
        private readonly IRabbitService mqService;
        private readonly MqSettings mqSettings;
        //private readonly IValidator<DistributeRequest> validator;
        private readonly IClientService clientService;

        public DistributorController(
            IRabbitService mqService,
            MqSettings mqSettings,
            //IValidator<DistributeRequest> validator,
            IClientService clientService
            )
        {
            this.mqService = mqService;
            this.mqSettings = mqSettings;
            //this.validator = validator;
            this.clientService = clientService;
        }


        /// <summary>
        /// Перераспределить шаблоны для группы работ
        /// </summary>
        /// <returns></returns>
        [HttpPost(ApiRoutes.Distributor.Distribute)]
        public async Task<IActionResult> Distribute([FromBody] DistributeRequest request)
        {
            //var resultValidate = await validator.ValidateAsync(request);
            //if (!resultValidate.IsValid)
            //    return BadRequest(new Response(resultValidate.Errors));

            var requestToMq = new TemplateDistributorMq
            {
                JobGroupId = request.JobGroupId,
                Initiator = new HistoryInitiator
                {
                    InitiatorComment = "Через API отправлен запрос на распределение шаблонов",
                    InitiatorIp = clientService.GetClientIp()?.ToString(),
                    InitiatorParrComponentId = ParrComponentsEnum.Api
                }
            };

            //var jsonOptions = new JsonSerializerOptions
            //{
            //    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            //};
            //var msg = JsonSerializer.Serialize(requestToMq, jsonOptions);

            //var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new[] { msg });
            var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new List<object> { requestToMq });

            if (sendResult.IsSuccess)
                return Created("", new Response<string?>(null, true, new List<ErrorModel>(), "Отправлен запрос на перераспределение регламентных работ."));
            else
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при отправке данных." } }));

        }
    }
}
