using NeonSprawl.Server.Game.Targeting;

namespace NeonSprawl.Server.Game.Combat;

/// <summary>Maps <c>GET /game/world/combat-targets</c> (NEO-83).</summary>
public static class CombatTargetsWorldApi
{
    public static WebApplication MapCombatTargetsWorldApi(this WebApplication app)
    {
        app.MapGet(
            "/game/world/combat-targets",
            (ICombatEntityHealthStore healthStore) =>
            {
                var ids = PrototypeTargetRegistry.GetPrototypeTargetIdsInOrder();
                var targets = new List<CombatTargetJson>(ids.Count);
                foreach (var id in ids)
                {
                    if (!healthStore.TryGet(id, out var snapshot))
                    {
                        throw new InvalidOperationException(
                            $"Prototype combat target '{id}' is registered but missing from {nameof(ICombatEntityHealthStore)}.");
                    }

                    targets.Add(
                        new CombatTargetJson
                        {
                            TargetId = snapshot.TargetId,
                            MaxHp = snapshot.MaxHp,
                            CurrentHp = snapshot.CurrentHp,
                            Defeated = snapshot.Defeated,
                        });
                }

                return Results.Json(
                    new CombatTargetsListResponse
                    {
                        SchemaVersion = CombatTargetsListResponse.CurrentSchemaVersion,
                        Targets = targets,
                    });
            });

        return app;
    }
}
