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

namespace PARR.TemplateMatcher.Services.Implementations.SimpleSync;

internal class FilterUnitsStage : ISimpleSyncStage
{
    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<SimpleSyncContext> ExecuteAsync(SimpleSyncContext context, CancellationToken ct = default)
    {
        var filtered = await _filterService.GetUnitsByJobFilterAsync(context.JobId, null, ct);

        if (filtered != null)
        {
            context.FilteredUnitIds = filtered.Select(u => u.Id).ToHashSet();
            context.UnitNames = filtered.ToDictionary(u => u.Id, u => u.Name);
        }

        _logger.LogDebug("Job '{JobName}' ({JobId}): отфильтровано {Count} юнитов",
            context.JobName, context.JobId, context.FilteredUnitIds.Count);

        return context;
    }
}