using Microsoft.AspNetCore.SignalR;

namespace Prospect.Server.Api.Hubs;

public class CycleHub : Hub
{
    private readonly SignalRConnectionRegistry _registry;

    public CycleHub(SignalRConnectionRegistry registry)
    {
        _registry = registry;
    }

    public override async Task OnConnectedAsync()
    {
        // The client connects with the SignalR URL returned by GetSignalRConnection, which
        // carries a `uid` query param — use it to map this connection to the player so
        // server-initiated messages can target a single player instead of everyone.
        var uid = Context.GetHttpContext()?.Request.Query["uid"].ToString();
        if (!string.IsNullOrEmpty(uid))
            _registry.Add(uid, Context.ConnectionId);
        Console.WriteLine("Connected {0} (uid={1})", Context.ConnectionId, uid);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        _registry.Remove(Context.ConnectionId);
        await base.OnDisconnectedAsync(exception);
    }
}
