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

namespace GameList.Endpoints;

public static class SuggestEndpoints
{
    public static void MapSuggestEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/suggestions").RequireAuthorization();

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

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

        group.MapPost("/", async ([FromBody] SuggestionRequest request, HttpContext ctx, AppDbContext db, SuggestionWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

            return await service.CreateAsync(player, request);
        }).AddEndpointFilter(new PhaseOrJokerFilter());

        group.MapDelete("/{id:int}", async (int id, HttpContext ctx, AppDbContext db, SuggestionWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

            var isAdmin = await EndpointHelpers.IsAdmin(ctx, db);
            return await service.DeleteAsync(player, isAdmin, id);
        });

        group.MapPut("/{id:int}", async (int id, [FromBody] SuggestionRequest request, HttpContext ctx, AppDbContext db, SuggestionWorkflowService service) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null)
                return EndpointHelpers.UnauthorizedError();

            var isAdmin = player.IsAdmin;
            return await service.UpdateAsync(player, isAdmin, id, request);
        });

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

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

