using GameList.Contracts;
using GameList.Data;
using GameList.Infrastructure;
using GameList.Domain;

namespace GameList.Endpoints;

public static class VoteEndpoints
{
    public static void MapVoteEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/votes").RequireAuthorization().AddEndpointFilter(new PhaseRequirementFilter(Phase.Vote));

        group.MapGet("/mine", async (HttpContext ctx, AppDbContext db, VoteWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

            return await service.GetMineAsync(player);
        });

        group.MapPost("/", async (VoteRequest request, HttpContext ctx, AppDbContext db, VoteWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();
            return await service.UpsertAsync(player, request);
        });

        group.MapPost("/finalize", async (VoteFinalizeRequest request, HttpContext ctx, AppDbContext db, VoteWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

            return await service.SetFinalizeAsync(player, request);
        });
    }
}

