using Microsoft.Extensions.Logging;
using PARR.TemplateMatcher.Services.GroupedSync;

namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;

internal class ResolveConflictsStage : IGroupedSyncStage
{
    private readonly IUnitInTemplateConflictMapper _conflictMapper;
    private readonly ILogger<ResolveConflictsStage> _logger;

    public string StageName => "Разрешение конфликтов";

    public ResolveConflictsStage(IUnitInTemplateConflictMapper conflictMapper, ILogger<ResolveConflictsStage> logger)
    {
        _conflictMapper = conflictMapper;
        _logger = logger;
    }

    public async Task<GroupedSyncContext> ExecuteAsync(GroupedSyncContext context, CancellationToken ct = default)
    {
        var mapping = await _conflictMapper.BuildMappingAsync(context.FilteredUnits, context.MaxJob, ct);

        if (!mapping.Any())
            throw new GroupedSyncEarlyExitException("Нет связей после разрешения конфликтов");

        context.ReverseMapping = mapping;

        _logger.LogDebug("JobGroup '{JobGroupName}' ({JobGroupId}): разрешено конфликтов, связей={Count}",
            context.JobGroupName, context.JobGroupId, mapping.Count);

        return context;
    }
}