using EonaCat.LogStack.Core;
using System;
using System.Collections.Generic;
using System.Linq;

namespace EonaCat.LogStack.Boosters;

/// <summary>
/// Deduplication booster that filters duplicate messages within a time window
/// </summary>
public sealed class DeduplicationBooster : BoosterBase
{
    private readonly TimeSpan _window;
    private readonly Dictionary<string, DateTime> _seenMessages = new();
    private readonly object _lock = new object();

    public DeduplicationBooster(TimeSpan? window = null) : base("Deduplication")
    {
        _window = window ?? TimeSpan.FromSeconds(10);
    }

    public override bool Boost(ref LogEventBuilder builder)
    {
        lock (_lock)
        {
            var now = DateTime.UtcNow;

            // Clean old entries
            var oldEntries = _seenMessages
                .Where(kvp => (now - kvp.Value) > _window)
                .Select(kvp => kvp.Key)
                .ToList();

            foreach (var key in oldEntries)
            {
                _seenMessages.Remove(key);
            }

            // For now, don't deduplicate as we don't have access to message in ref struct
            // This can be enhanced when builder provides access
            return true;
        }
    }
}
