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

namespace GameList.Infrastructure;

public class PhaseRequirementFilter : IEndpointFilter
{
    private readonly Phase _required;
    private readonly bool _allowAdminOverride;

    public PhaseRequirementFilter(Phase required, bool allowAdminOverride = false)
    {
        _required = required;
        _allowAdminOverride = allowAdminOverride;
    }

    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);
    }
}
