using System.Collections.Concurrent;
using Predictalytics.Application.Interfaces;
using Predictalytics.Domain.Enums;

namespace Predictalytics.Application.Services;

public class PlatformStatisticsService : IPlatformStatisticsService
{
    private readonly ConcurrentDictionary<PlatformType, PlatformStats> _stats = new();

    public void TrackMarketSync(PlatformType platform, int count = 1)
    {
        var stats = _stats.GetOrAdd(platform, _ => new PlatformStats());
        lock (stats) stats.MarketsSynced += count;
    }

    public void TrackTraderDiscovery(PlatformType platform, int count = 1)
    {
        var stats = _stats.GetOrAdd(platform, _ => new PlatformStats());
        lock (stats) stats.TradersDiscovered += count;
    }

    public void TrackTradeActivity(PlatformType platform, int count = 1)
    {
        var stats = _stats.GetOrAdd(platform, _ => new PlatformStats());
        lock (stats) stats.TradesProcessed += count;
    }

    public void TrackDuplicateError(PlatformType platform, int count = 1)
    {
        var stats = _stats.GetOrAdd(platform, _ => new PlatformStats());
        lock (stats) stats.DuplicateErrors += count;
    }

    public void TrackTradersAnalyzed(PlatformType platform, int count = 1)
    {
        var stats = _stats.GetOrAdd(platform, _ => new PlatformStats());
        lock (stats) stats.TradersAnalyzed += count;
    }

    public Dictionary<PlatformType, PlatformStats> GetAndResetStats()
    {
        var result = new Dictionary<PlatformType, PlatformStats>();
        var platforms = Enum.GetValues<PlatformType>();

        foreach (var p in platforms)
        {
            if (_stats.TryRemove(p, out var stats))
            {
                result[p] = stats;
            }
        }

        return result;
    }
}
