using Microsoft.Extensions.Logging;
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.Domain.Enums;
using PARR.TemplateMatcher.Services.Interfaces;
using PARR.TemplateMatcher.Services.SimpleSync;

namespace PARR.TemplateMatcher.Services.Implementations.SimpleSync;

internal class UpdateNamesStage : ISimpleSyncWriteStage
{
    private readonly ITemplateMqPublisher _mqPublisher;
    private readonly ILogger<UpdateNamesStage> _logger;

    public string StageName => "Обновление имён";

    public UpdateNamesStage(ITemplateMqPublisher mqPublisher, ILogger<UpdateNamesStage> logger)
    {
        _mqPublisher = mqPublisher;
        _logger = logger;
    }

    public async Task<SimpleSyncContext> ExecuteAsync(SimpleSyncContext context, CancellationToken ct = default)
    {
        foreach (var (template, expectedName) in context.TemplatesToRename)
        {
            var updateRequest = new TemplateUpdaterMessage
            {
                TemplateId = template.Id,
                JobId = context.JobId,
                UnitId = template.UnitId,
                Name = expectedName,
                IsActiveTemplate = template.IsActiveTemplate,
                IsActiveSchedule = template.IsActiveSchedule,
                IsNew = false,
                Index = template.Index,
                StatusTypeId = TemplateStatusTypeEnum.Used,
                Initiator = context.Initiator,
                UnitsInTemplate = new List<UnitInTemplateMessage>()
            };

            await _mqPublisher.PublishUpdateAsync(updateRequest);

            _logger.LogDebug("Job '{JobName}' ({JobId}): шаблон '{TemplateName}' ({TemplateId}) для Unit {Unit} переименован в '{NewName}'",
                context.JobName, context.JobId, template.Name, template.Id,
                context.FormatUnit(template.UnitId), expectedName);
        }

        return context;
    }
}