using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.WebApi.Hubs;

/// <summary>
/// SignalR Hub for broadcasting token-related notifications to connected BFF clients.
/// This hub is used internally between CMS and BFF services.
/// </summary>
public class TokenNotificationHub : Hub
{
    private readonly ILogger<TokenNotificationHub> _logger;

    public TokenNotificationHub(ILogger<TokenNotificationHub> logger)
    {
        _logger = logger;
    }

    public override async Task OnConnectedAsync()
    {
        _logger.LogInformation("Client connected to TokenNotificationHub: {ConnectionId}", Context.ConnectionId);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        _logger.LogInformation("Client disconnected from TokenNotificationHub: {ConnectionId}, Exception: {Exception}", 
            Context.ConnectionId, exception?.Message);
        await base.OnDisconnectedAsync(exception);
    }

    /// <summary>
    /// Subscribe to notifications for a specific user
    /// </summary>
    public async Task SubscribeToUser(long userId)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, $"user_{userId}");
        _logger.LogInformation("Client {ConnectionId} subscribed to user_{UserId}", Context.ConnectionId, userId);
    }

    /// <summary>
    /// Unsubscribe from notifications for a specific user
    /// </summary>
    public async Task UnsubscribeFromUser(long userId)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user_{userId}");
        _logger.LogInformation("Client {ConnectionId} unsubscribed from user_{UserId}", Context.ConnectionId, userId);
    }
}
