using Microsoft.Extensions.Logging;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.DomainServices.Interfaces;
using PARR.TemplateTaskGenerator.Settings;
using System.Text.Json;

namespace PARR.TemplateTaskGenerator
{
    internal class TemplateTaskGenerator : ITemplateTaskGenerator
    {
        private readonly ILogger<TemplateTaskGenerator> logger;
        private readonly IUnitFilterService unitFilterService;
        private readonly MqSettings mqSettings;
        private readonly IMqService mqService;

        public TemplateTaskGenerator(
            ILogger<TemplateTaskGenerator> logger,
            IUnitFilterService unitFilterService,
            MqSettings mqSettings,
            IMqService mqService
            )
        {
            this.logger = logger;
            this.unitFilterService = unitFilterService;
            this.mqSettings = mqSettings;
            this.mqService = mqService;
        }


        public async Task GenerateTemplateTaskAsync(Guid jobId)
        {
            //var unitIdsToCreateTemplate = await unitFilterService.GetUnitsIdByJobFilterWithTemplateStatusAsync(jobId, false);
            //todo: !!!!!!!! исправить в этом месте !!!!!!!!
            IEnumerable<Guid>? unitIdsToCreateTemplate = null;

            if (unitIdsToCreateTemplate == null || !unitIdsToCreateTemplate.Any())
                return;

            foreach (var unitId in unitIdsToCreateTemplate)
            {
                var mqRequest = new TemplateGeneratorMq
                {
                    UnitsInTemplate=new List<Guid>(),
                    JobId = jobId,
                    UnitId = unitId,
                    HistoryInitiator = new HistoryInitiator { InitiatorComment = "Запрос на создание шаблона", InitiatorParrComponentId = ParrComponentsEnum.TemplateTaskGenerator },
                    UnitsInTemplate = new List<Guid>()
                    
                };

                var msg = JsonSerializer.Serialize(mqRequest);

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

                if (result.IsSuccess)
                    logger.LogInformation($"Отправлен запрос на создание шаблона: {msg}");
                else
                    logger.LogError($"Ошибка при отправке запроса на создание шаблона: {msg}");
            }
        }
    }
}
