using Microsoft.Extensions.Logging;
using PARR.TemplateMatcher.Services.Interfaces;
using PARR.TemplateMatcher.Services.SimpleSync;

namespace PARR.TemplateMatcher.Services.Implementations.SimpleSync;

internal class DeactivateTemplatesStage : ISimpleSyncWriteStage
{
    private readonly ITemplateDeactivator _deactivator;
    private readonly ILogger<DeactivateTemplatesStage> _logger;

    public string StageName => "Деактивация шаблонов";

    public DeactivateTemplatesStage(ITemplateDeactivator deactivator, ILogger<DeactivateTemplatesStage> logger)
    {
        _deactivator = deactivator;
        _logger = logger;
    }

    public async Task<SimpleSyncContext> ExecuteAsync(SimpleSyncContext context, CancellationToken ct = default)
    {
        foreach (var template in context.UnusedTemplates)
        {
            _logger.LogInformation("Job '{JobName}' ({JobId}): деактивация шаблона '{TemplateName}' ({TemplateId}), Unit {Unit}",
                context.JobName, context.JobId, template.Name, template.Id,
                context.FormatUnit(template.UnitId));

            await _deactivator.DeactivateTemplateAsync(template, context.Initiator);
        }

        return context;
    }
}