using Backend.Data;
using Backend.Endpoints;
using Backend.Services;

namespace Backend.Security;

public sealed class AdminSessionFilter(IUserSessionService userSessionService, AwardsDbContext db) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var session = await userSessionService.ResolveSessionAsync(context.HttpContext, context.HttpContext.RequestAborted);
        if (session is null)
        {
            return Results.Unauthorized();
        }

        if (!AdminRoles.CanAccessAdmin(session.Role))
        {
            return Results.Json(new { message = "Admin access requires an elevated role." }, statusCode: StatusCodes.Status403Forbidden);
        }

        var teamMember = await AuthEndpoints.FindTeamMemberForSessionAsync(db, session, context.HttpContext.RequestAborted);
        if (teamMember is not null)
        {
            if (!teamMember.IsActive)
            {
                return Results.Unauthorized();
            }

            if (teamMember.MustChangePassword)
            {
                return Results.Json(new { message = "Bitte ändere zuerst dein temporäres Passwort." }, statusCode: StatusCodes.Status403Forbidden);
            }

            session.DisplayName = teamMember.DisplayName;
            session.Role = AdminRoles.Normalize(teamMember.Role);
        }

        context.HttpContext.SetCurrentSession(session);
        return await next(context);
    }
}
