using System.Security.Claims;
using Microsoft.IdentityModel.JsonWebTokens;

namespace Web.Api.Extensions;

public static class ClaimsPrincipalExtensions
{
    public static int? GetMemberID(this ClaimsPrincipal user)
    {
        var memberIDClaim = user.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;

        if (int.TryParse(memberIDClaim, out var memberID))
        {
            return memberID;
        }

        return null;
    }

    /// <summary>
    /// 인증 필수 Endpoints에서 사용. 토큰이 없으면 UnauthorizedAccessException.
    /// </summary>
    public static int GetRequiredMemberID(this ClaimsPrincipal user)
    {
        return user.GetMemberID() ?? throw new UnauthorizedAccessException("인증 정보가 없습니다.");
    }
}