using NeonSprawl.Server.Game.PositionState;

namespace NeonSprawl.Server.Game.Gigs;

/// <summary>Maps <c>GET /game/players/{{id}}/gig-progression</c> — read snapshot (NEO-44).</summary>
public static class GigProgressionSnapshotApi
{
    public static WebApplication MapGigProgressionSnapshotApi(this WebApplication app)
    {
        app.MapGet(
            "/game/players/{id}/gig-progression",
            (string id, IPositionStateStore positions, IPlayerGigProgressionStore gigStore) =>
            {
                var trimmedId = id.Trim();
                if (trimmedId.Length == 0 || !positions.TryGetPosition(trimmedId, out _))
                {
                    return Results.NotFound();
                }

                return Results.Json(BuildSnapshot(trimmedId, gigStore));
            });

        return app;
    }

    internal static GigProgressionSnapshotResponse BuildSnapshot(
        string playerId,
        IPlayerGigProgressionStore store)
    {
        var xpByGig = store.GetXpTotals(playerId);
        xpByGig.TryGetValue(GigProgressionConstants.PrototypeMainGigId, out var xp);

        return new GigProgressionSnapshotResponse
        {
            PlayerId = playerId,
            MainGigId = GigProgressionConstants.PrototypeMainGigId,
            Gigs =
            [
                new GigProgressionRowJson
                {
                    Id = GigProgressionConstants.PrototypeMainGigId,
                    Xp = xp,
                    Level = GigProgressionConstants.PrototypeFixedLevel,
                },
            ],
            SchemaVersion = GigProgressionSnapshotResponse.CurrentSchemaVersion,
        };
    }
}
