using System.Security.Claims;
using ERPCore.Domain.Entities;

namespace ERPCore.Infra.Auth;

/// <summary>
/// Resolves the audit actor from the current HTTP request's principal
/// (token `sub` / NameIdentifier). Falls back to <see cref="SystemActor"/>
/// when the request is unauthenticated (e.g. health checks, seeding).
/// </summary>
public sealed class CurrentUser : ICurrentUser
{
    public const string SystemActor = "system";

    private readonly IHttpContextAccessor _accessor;

    public CurrentUser(IHttpContextAccessor accessor) => _accessor = accessor;

    public bool IsAuthenticated =>
        _accessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;

    public string UserId
    {
        get
        {
            var user = _accessor.HttpContext?.User;
            var sub = user?.FindFirstValue(ClaimTypes.NameIdentifier)
                      ?? user?.FindFirstValue("sub");
            return string.IsNullOrWhiteSpace(sub) ? SystemActor : sub;
        }
    }

    public int AuditUserId => int.TryParse(UserId, out var id) ? id : User.SystemUserId;
}
