// EN: Custom user ID provider for SignalR hub.
// VI: Custom user ID provider cho SignalR hub.

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

namespace OrderService.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: Enables targeting specific users across multiple connections/devices.
/// VI: Cho phép nhắm đến user cụ thể qua nhiều kết nối/thiết bị.
/// </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;
    }
}
