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

namespace GameList.Endpoints;

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

        group.MapGet("/state", async (HttpContext ctx, AppDbContext db) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null) return Results.Unauthorized();
            var phase = await EndpointHelpers.GetPhase(db, player.Id);

            var state = await db.AppState.AsNoTracking().FirstAsync();
            var summary = new
            {
                CurrentPhase = phase,
                player.VotesFinal,
                player.HasJoker,
                state.ResultsOpen,
                state.UpdatedAt,
                Players = await db.Players.CountAsync(),
                Suggestions = await db.Suggestions.CountAsync(),
                Votes = await db.Votes.CountAsync()
            };
            return Results.Ok(summary);
        });

        group.MapGet("/me", async (HttpContext ctx, AppDbContext db) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null) return Results.Unauthorized();
            var phase = await EndpointHelpers.GetPhase(db, player.Id);
            return Results.Ok(new { player.Id, player.DisplayName, player.Username, player.IsAdmin, CurrentPhase = phase, player.VotesFinal, player.HasJoker });
        });

        group.MapPost("/me/phase/next", async (HttpContext ctx, AppDbContext db, IConfiguration config) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null) return Results.Unauthorized();
            var isAdmin = await EndpointHelpers.IsAdmin(ctx, db);

            var next = NextPhase(player.CurrentPhase);
            var appState = await db.AppState.FirstAsync();

            if (next == Phase.Results && !appState.ResultsOpen)
            {
                return Results.BadRequest(new { error = "Results are locked until the admin enables them." });
            }

            player.CurrentPhase = next;
            player.VotesFinal = false; // moving forward clears any prior finalize
            await db.SaveChangesAsync();
            return Results.Ok(new { player.CurrentPhase, appState.ResultsOpen });
        });

        group.MapPost("/me/phase/prev", async (HttpContext ctx, AppDbContext db, IConfiguration config) =>
        {
            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null) return Results.Unauthorized();
            var isAdmin = await EndpointHelpers.IsAdmin(ctx, db);
            if (!isAdmin)
            {
                return Results.BadRequest(new { error = "Only admins can move backward." });
            }

            player.CurrentPhase = PrevPhase(player.CurrentPhase);
            player.VotesFinal = false;
            await db.SaveChangesAsync();
            var appState = await db.AppState.AsNoTracking().FirstAsync();
            return Results.Ok(new { player.CurrentPhase, appState.ResultsOpen });
        });

        group.MapPost("/me/name", async ([FromBody] SetNameRequest request, HttpContext ctx, AppDbContext db) =>
        {
            var name = EndpointHelpers.TrimTo(request.Name, 16);
            if (string.IsNullOrWhiteSpace(name))
            {
                return Results.BadRequest(new { error = "Name is required and must be <= 16 characters." });
            }

            var player = await EndpointHelpers.GetAuthenticatedPlayer(ctx, db);
            if (player is null) return Results.Unauthorized();

            player.DisplayName = name;
            await db.SaveChangesAsync();
            return Results.Ok(new { player.Id, player.DisplayName });
        });
    }

    private static Phase NextPhase(Phase current) => current switch
    {
        Phase.Suggest => Phase.Vote,
        Phase.Reveal => Phase.Vote, // legacy safety
        Phase.Vote => Phase.Results,
        _ => Phase.Results
    };

    private static Phase PrevPhase(Phase current) => current switch
    {
        Phase.Results => Phase.Vote,
        Phase.Vote => Phase.Suggest,
        Phase.Reveal => Phase.Suggest, // legacy safety
        _ => Phase.Suggest
    };
}
