using System.Security.Claims;

namespace TakeoutSaaS.Shared.Web.Security;

/// <summary>
/// ClaimsPrincipal 便捷扩展
/// </summary>
public static class ClaimsPrincipalExtensions
{
    /// <summary>
    /// 获取当前用户 Id（不存在时返回 0）。
    /// </summary>
    public static long GetUserId(this ClaimsPrincipal? principal)
    {
        if (principal == null)
        {
            return 0;
        }

        var identifier = principal.FindFirstValue(ClaimTypes.NameIdentifier)
                         ?? principal.FindFirstValue("sub");

        return long.TryParse(identifier, out var userId)
            ? userId
            : 0;
    }
}
