using GameList.Data;
using GameList.Domain;
using GameList.Contracts;
using Microsoft.AspNetCore.Mvc;
using GameList.Infrastructure;

namespace GameList.Endpoints;

public static class AdminEndpoints
{
    public static void MapAdminEndpoints(this IEndpointRouteBuilder app)
    {
        var admin = app.MapGroup("/api/admin").RequireAuthorization().AddEndpointFilter<AdminOnlyFilter>();

        admin.MapPost("/results", async ([FromBody] ResultsOpenRequest request, AdminWorkflowService service) =>
        {
            return await service.SetResultsOpenAsync(request);
        });

        admin.MapGet("/vote-status", async (AdminWorkflowService service) =>
        {
            return await service.GetVoteStatusAsync();
        });

        admin.MapPost("/joker", async ([FromBody] GrantJokerRequest request, AdminWorkflowService service) =>
        {
            return await service.GrantJokerAsync(request);
        });

        admin.MapDelete("/players/{playerId:guid}", async (Guid playerId, AdminWorkflowService service) =>
        {
            return await service.DeletePlayerAsync(playerId);
        });

        admin.MapPost("/link-suggestions", async ([FromBody] LinkSuggestionsRequest request, HttpContext ctx, AppDbContext db, AdminWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

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

        admin.MapPost("/unlink-suggestions", async ([FromBody] UnlinkSuggestionsRequest request, HttpContext ctx, AppDbContext db, AdminWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

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

        admin.MapPost("/reset", async (AdminWorkflowService service) =>
        {
            return await service.ResetAsync();
        });

        admin.MapPost("/factory-reset", async (AdminWorkflowService service) =>
        {
            return await service.FactoryResetAsync();
        });
    }
}

