using Application.Abstractions.Cache;
using Application.Abstractions.Chat;
using Microsoft.AspNetCore.SignalR;
using StackExchange.Redis;
using Web.Api.Hubs;

namespace Web.Api.Services;

public sealed class KickSubscriberService(
    IConnectionMultiplexer redis,
    IHubContext<ChatHub, IChatHubClient> hubContext
) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await redis.GetSubscriber().SubscribeAsync(
            RedisChannel.Literal(CacheKeys.ChatKickChannel),
            async (_, connectionId) =>
            {
                if (!connectionId.IsNullOrEmpty)
                    await hubContext.Clients.Client(connectionId!).Kick();
            });
    }

    public async Task StopAsync(CancellationToken cancellationToken)
        => await redis.GetSubscriber().UnsubscribeAsync(
            RedisChannel.Literal(CacheKeys.ChatKickChannel));
}
