using GameList.Data;
using GameList.Domain;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace GameList.Endpoints;

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

        admin.MapPost("/phase", async ([FromBody] Contracts.PhaseRequest request, HttpContext ctx, AppDbContext db, IConfiguration config) =>
        {
            if (!await EndpointHelpers.IsAdmin(ctx, db, config)) return Results.Unauthorized();

            var state = await db.AppState.FirstAsync();
            state.CurrentPhase = request.Phase;
            state.UpdatedAt = DateTimeOffset.UtcNow;
            await db.SaveChangesAsync();
            return Results.Ok(new { state.CurrentPhase, state.UpdatedAt });
        });

        admin.MapPost("/reset", async (HttpContext ctx, AppDbContext db, IConfiguration config) =>
        {
            if (!await EndpointHelpers.IsAdmin(ctx, db, config)) return Results.Unauthorized();

            await db.Votes.ExecuteDeleteAsync();
            await db.Suggestions.ExecuteDeleteAsync();

            var state = await db.AppState.FirstAsync();
            state.CurrentPhase = Phase.Suggest;
            state.UpdatedAt = DateTimeOffset.UtcNow;
            await db.SaveChangesAsync();

            return Results.Ok(new { state.CurrentPhase, state.UpdatedAt });
        });

        admin.MapPost("/factory-reset", async (HttpContext ctx, AppDbContext db, IConfiguration config) =>
        {
            if (!await EndpointHelpers.IsAdmin(ctx, db, config)) return Results.Unauthorized();

            await using var tx = await db.Database.BeginTransactionAsync();

            await db.Votes.ExecuteDeleteAsync();
            await db.Suggestions.ExecuteDeleteAsync();
            await db.Players.ExecuteDeleteAsync();
            await db.AppState.ExecuteDeleteAsync();

            var fresh = EndpointHelpers.NewAppState();
            db.AppState.Add(fresh);
            await db.SaveChangesAsync();

            await tx.CommitAsync();

            return Results.Ok(new { fresh.CurrentPhase, fresh.UpdatedAt });
        });
    }
}
