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.Settings;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using PARR.Constants;
using System.Text.Json;

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

        public DistributorController(
            IMqService mqService,
            MqSettings mqSettings,
            IValidator<DistributeRequest> validator
            )
        {
            this.mqService = mqService;
            this.mqSettings = mqSettings;
            this.validator = validator;
        }


        /// <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
            };

            var msg = JsonSerializer.Serialize(requestToMq);

            var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new[] { msg });

            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 = "Ошибка при отправке данных." } }));

        }
    }
}
