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

namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;

internal class FilterUnitsStage : IGroupedSyncStage
{
    private readonly IUnitFilterService _filterService;
    private readonly ILogger<FilterUnitsStage> _logger;

    public string StageName => "Фильтрация юнитов";

    public FilterUnitsStage(IUnitFilterService filterService, ILogger<FilterUnitsStage> logger)
    {
        _filterService = filterService;
        _logger = logger;
    }

    public async Task<GroupedSyncContext> ExecuteAsync(GroupedSyncContext context, CancellationToken ct = default)
    {
        var result = await _filterService.GetUnitsByJobFilterAsync(context.MaxJob.Id, null, ct);

        if (result == null || !result.Any())
            throw new GroupedSyncEarlyExitException("Фильтры не дали Unit'ов с подходящими связями");

        context.FilteredUnits = result.ToList();
        context.UnitNames = result.ToDictionary(u => u.Id, u => u.Name);

        _logger.LogDebug("JobGroup '{JobGroupName}' ({JobGroupId}): отфильтровано {Count} юнитов",
            context.JobGroupName, context.JobGroupId, context.FilteredUnits.Count);

        return context;
    }
}