using System.Collections.Concurrent;

namespace Ikar.Server.Infrastructure;

public sealed class PresenceTracker
{
    private readonly ConcurrentDictionary<Guid, int> _connections = new();

    public void MarkOnline(Guid userId)
    {
        _connections.AddOrUpdate(userId, 1, (_, current) => current + 1);
    }

    public void MarkOffline(Guid userId)
    {
        while (true)
        {
            if (!_connections.TryGetValue(userId, out var current))
            {
                return;
            }

            if (current <= 1)
            {
                if (_connections.TryRemove(userId, out _))
                {
                    return;
                }

                continue;
            }

            if (_connections.TryUpdate(userId, current - 1, current))
            {
                return;
            }
        }
    }

    public bool IsOnline(Guid userId) => _connections.ContainsKey(userId);
}
