using Microsoft.AspNetCore.Http;

namespace SIGCM2.Api.Middleware;

/// UDT-010 — post-auth middleware that reads the JWT "sub" claim and stores the
/// resolved ActorUserId in HttpContext.Items. Anonymous requests leave it unset.
/// ActorRoleId is reserved for a future batch (rol code → id resolution).
public sealed class AuditActorMiddleware
{
    public const string ItemActorUserId = "audit:actorUserId";

    private readonly RequestDelegate _next;

    public AuditActorMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext ctx)
    {
        if (ctx.User.Identity?.IsAuthenticated == true)
        {
            var sub = ctx.User.FindFirst("sub")?.Value;
            if (int.TryParse(sub, out var userId))
            {
                ctx.Items[ItemActorUserId] = userId;
            }
        }

        await _next(ctx);
    }
}
