using Microsoft.Extensions.Logging;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;

namespace PARR.Core.Services.UnitFilterService.Matchers;

/// <summary>
/// Применяет Umbrella-фильтр по количеству связей.
/// </summary>
internal class UmbrellaFilter : IUmbrellaFilter
{
    private readonly ILogger<UmbrellaFilter> logger;

    public UmbrellaFilter(ILogger<UmbrellaFilter> logger)
    {
        this.logger = logger;
    }

    public List<UnitFilterMatchResult> Apply(
        List<UnitFilterMatchResult> contexts,
        Job job)
    {
        if (job.Group?.GroupType?.Code != JobGroupTypesEnum.Umbrella)
            return contexts;

        var min = job.MinValueRelationships ?? 0;
        var max = job.MaxValueRelationships ?? int.MaxValue;
        var isParentDirection = job.IsParentRelationships == true;

        if (min == 0 && max == int.MaxValue)
            return contexts;

        logger.LogDebug("UmbrellaFilter: Min={Min}, Max={Max}, IsParent={IsParent}, Вход={Count}",
            min, max, isParentDirection, contexts.Count);

        var result = new List<UnitFilterMatchResult>(contexts.Count);

        foreach (var context in contexts)
        {
            int count = isParentDirection
                ? context.ValidParentIds.Count
                : context.ValidChildIds.Count;

            if (count >= min && count <= max)
                result.Add(context);
        }

        logger.LogDebug("UmbrellaFilter: Выход={Count} (отфильтровано {Filtered})",
            result.Count, contexts.Count - result.Count);

        return result;
    }
}