using Microsoft.AspNetCore.Http;
using SIGCM2.Application.Audit;

namespace SIGCM2.Infrastructure.Audit;

/// UDT-010 — scoped IAuditContext implementation backed by HttpContext.Items entries
/// populated by the middleware pipeline (CorrelationIdMiddleware + AuditActorMiddleware).
/// Returns defaults (null / Guid.Empty) when no HttpContext is available.
public sealed class AuditContext : IAuditContext
{
    private readonly IHttpContextAccessor _accessor;

    public AuditContext(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }

    private HttpContext? Http => _accessor.HttpContext;

    public int? ActorUserId =>
        Http?.Items.TryGetValue("audit:actorUserId", out var v) == true ? v as int? : null;

    // Reserved: the pipeline does not currently resolve rol code -> id. Logger-side resolution
    // may populate this in a future batch.
    public int? ActorRoleId =>
        Http?.Items.TryGetValue("audit:actorRoleId", out var v) == true ? v as int? : null;

    public string? Ip =>
        Http?.Items.TryGetValue("audit:ip", out var v) == true ? v as string : null;

    public string? UserAgent =>
        Http?.Items.TryGetValue("audit:userAgent", out var v) == true ? v as string : null;

    public Guid CorrelationId =>
        Http?.Items.TryGetValue("audit:correlationId", out var v) == true
            ? (v as Guid?) ?? Guid.Empty
            : Guid.Empty;
}
