using System.Security.Claims;
using Microsoft.AspNetCore.SignalR;

namespace ChatService.API.Hubs;

/// <summary>
/// EN: Custom user ID provider that extracts user ID from JWT claims.
/// VI: Custom user ID provider lấy user ID từ JWT claims.
/// </summary>
/// <remarks>
/// EN: This enables sending messages to specific users regardless of which device they're connected from.
/// VI: Cho phép gửi tin nhắn đến user cụ thể bất kể họ đang kết nối từ thiết bị nào.
/// </remarks>
public class ClaimsUserIdProvider : IUserIdProvider
{
    /// <inheritdoc/>
    public string? GetUserId(HubConnectionContext connection)
    {
        // EN: Try to get user ID from standard claim types
        // VI: Thử lấy user ID từ các claim types chuẩn
        return connection.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
            ?? connection.User?.FindFirst("sub")?.Value
            ?? connection.User?.FindFirst("user_id")?.Value;
    }
}
