using Application.Abstractions.Chat;
using Microsoft.AspNetCore.SignalR;

namespace Web.Api.Hubs;

public sealed class ChatHubService(
    IHubContext<ChatHub, IChatHubClient> hubContext, IChatConnectionTracker tracker
) : IChatHubService {

    public async Task BroadcastMessageAsync(ChatMessage message, CancellationToken ct = default)
    {
        await hubContext.Clients.All.ReceiveMessage(message);
    }

    public async Task BroadcastSystemMessageAsync(string message, CancellationToken ct = default)
    {
        await hubContext.Clients.All.ReceiveSystemMessage(message);
    }

    public async Task KickUserAsync(int memberID, CancellationToken ct = default)
    {
        var all = await tracker.GetAllAsync();
        var ids = all.Where(x => x.MemberID == memberID).Select(x => x.ConnectionId).ToList();

        foreach (var id in ids)
        {
            await hubContext.Clients.Client(id).Kick();
        }
    }
}