using GameList.Data;
using GameList.Domain;
using GameList.Endpoints;

namespace GameList.Infrastructure;

public class PhaseRequirementFilter(Phase required, bool allowAdminOverride = false) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var httpContext = context.HttpContext;
        var db = httpContext.RequestServices.GetRequiredService<AppDbContext>();
        var player = await EndpointHelpers.GetAuthenticatedPlayer(httpContext, db);
        if (player is null)
            return Results.Unauthorized();

        var phase = await EndpointHelpers.GetPhase(db, player.Id);
        if (phase != required && !(allowAdminOverride && player.IsAdmin))
        {
            return EndpointHelpers.PhaseMismatch(required, phase);
        }

        return await next(context);
    }
}
