using Microsoft.AspNetCore.Http;
using MiGu.DB.Abstractions.Runtime;
using MiGu.DB.Kernel.Conventions;

namespace MiGu.Server.Persistence;

/// <summary>从 JWT Claims 解析当前操作者，写入 IActorContextAccessor。</summary>
public sealed class HttpActorContextMiddleware
{
    private readonly RequestDelegate _next;

    public HttpActorContextMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext http, IActorContextAccessor actors)
    {
        var name = http.User?.Identity?.Name
            ?? http.User?.FindFirst("sub")?.Value
            ?? http.User?.FindFirst("unique_name")?.Value
            ?? "system";
        actors.Current = new HttpActorContext(name);
        try
        {
            await _next(http);
        }
        finally
        {
            actors.Current = SystemActorContext.Instance;
        }
    }

    private sealed class HttpActorContext : IActorContext
    {
        public HttpActorContext(string name) => Name = name;
        public string Name { get; }
    }
}
