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

namespace PARR.TemplateMatcher.Services.Implementations.SimpleSync;

internal class AllocateTemplatesStage : ISimpleSyncWriteStage
{
    private readonly ITemplateAllocationService _allocationService;
    private readonly ILogger<AllocateTemplatesStage> _logger;

    public string StageName => "Создание шаблонов";

    public AllocateTemplatesStage(
        ITemplateAllocationService allocationService,
        ILogger<AllocateTemplatesStage> logger)
    {
        _allocationService = allocationService;
        _logger = logger;
    }

    public async Task<SimpleSyncContext> ExecuteAsync(SimpleSyncContext context, CancellationToken ct = default)
    {
        const bool defaultUsedTemplateState = false;
        const bool defaultUsedScheduleState = false;

        foreach (var unitId in context.NewUnitIds)
        {
            var (isActiveTemplate, isActiveSchedule) = AutoControlResolver.ResolveInitStates(
                context.Job, context.Job.Group,
                defaultUsedTemplateState, defaultUsedScheduleState);

            var request = new TemplateAllocationRequest(
                TargetJob: context.Job,
                TargetUnitId: unitId,
                TargetUnit: null,
                Index: null,
                UnitsInTemplate: new List<UnitInTemplateMessage>(),
                IsActiveTemplate: isActiveTemplate,
                IsActiveSchedule: isActiveSchedule,
                Initiator: context.Initiator);

            await _allocationService.AllocateAsync(request);

            _logger.LogDebug("Job '{JobName}' ({JobId}): создан шаблон для Unit {Unit}",
                context.JobName, context.JobId, context.FormatUnit(unitId));
        }

        return context;
    }
}