using System.Security.Claims;

namespace ROLAC.API.Services.Logging;

/// <summary>
/// One place to resolve the acting user + request context from the current HttpContext, so the
/// "sub" claim quirk (JWT uses NameClaimType="sub" + MapInboundClaims=false, leaving
/// ClaimTypes.NameIdentifier null) lives in a single spot. Used by the audit interceptor,
/// IAuditLogger, the exception middleware, and the timestamp-stamping interceptor.
/// </summary>
public sealed class CurrentUserAccessor
{
    private readonly IHttpContextAccessor _http;

    public CurrentUserAccessor(IHttpContextAccessor http) => _http = http;

    /// <summary>The acting user id, or null when unauthenticated / off the request thread.</summary>
    public string? UserId =>
        _http.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier)
        ?? _http.HttpContext?.User.FindFirstValue("sub");

    /// <summary>The acting user id, or "system" for background/unauthenticated work.</summary>
    public string UserIdOrSystem => UserId ?? "system";

    public string? Email => _http.HttpContext?.User.FindFirstValue("email");

    public string? IpAddress => _http.HttpContext?.Connection.RemoteIpAddress?.ToString();

    public string? CorrelationId => _http.HttpContext?.TraceIdentifier;
}
