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

namespace GameList.Endpoints;

public static class StateEndpoints
{
    public static void MapStateEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapGet("/api/state", async (AppDbContext db) =>
        {
            var state = await db.AppState.AsNoTracking().FirstAsync();
            var summary = new
            {
                state.CurrentPhase,
                state.UpdatedAt,
                Players = await db.Players.CountAsync(),
                Suggestions = await db.Suggestions.CountAsync(),
                Votes = await db.Votes.CountAsync()
            };
            return Results.Ok(summary);
        });

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

        app.MapPost("/api/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 });
        });
    }
}
