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

namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;

internal class BuildGroupsStage : IGroupedSyncStage
{
    private readonly IGroupedTemplateBuilder _builder;
    private readonly ILogger<BuildGroupsStage> _logger;

    public string StageName => "Построение групп";

    public BuildGroupsStage(IGroupedTemplateBuilder builder, ILogger<BuildGroupsStage> logger)
    {
        _builder = builder;
        _logger = logger;
    }

    public async Task<GroupedSyncContext> ExecuteAsync(GroupedSyncContext context, CancellationToken ct = default)
    {
        var groups = await _builder.BuildAsync(context.ReverseMapping, context.JobGroup, context.MaxJob);

        if (!groups.Any())
            throw new GroupedSyncEarlyExitException("Нет данных после построения групп");

        context.TemplateGroups = groups;

        _logger.LogDebug("JobGroup '{JobGroupName}' ({JobGroupId}): построено {Count} групп",
            context.JobGroupName, context.JobGroupId, groups.Count);

        return context;
    }
}