using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Shared.Web.Security;

/// <summary>
/// 基于 HttpContext 的当前用户访问器。
/// </summary>
/// <remarks>
/// 初始化访问器。
/// </remarks>
public sealed class HttpContextCurrentUserAccessor(IHttpContextAccessor httpContextAccessor) : ICurrentUserAccessor
{
    /// <inheritdoc />
    public long UserId
    {
        get
        {
            var principal = httpContextAccessor.HttpContext?.User;
            if (principal == null || !principal.Identity?.IsAuthenticated == true)
            {
                return 0;
            }

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

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

    /// <inheritdoc />
    public bool IsAuthenticated => UserId != 0;
}
