namespace NeonSprawl.Server.Game.Gathering;

/// <summary>Maps <c>GET /game/world/resource-node-definitions</c> (NEO-60).</summary>
public static class ResourceNodeDefinitionsWorldApi
{
    public static WebApplication MapResourceNodeDefinitionsWorldApi(this WebApplication app)
    {
        app.MapGet(
            "/game/world/resource-node-definitions",
            (IResourceNodeDefinitionRegistry registry) =>
            {
                var defs = registry.GetDefinitionsInIdOrder();
                var nodes = new List<ResourceNodeDefinitionJson>(defs.Count);
                foreach (var d in defs)
                {
                    if (!registry.TryGetYield(d.NodeDefId, out var yieldRow) || yieldRow is null)
                    {
                        throw new InvalidOperationException(
                            $"Resource node definition '{d.NodeDefId}' has no yield row in the loaded catalog.");
                    }

                    nodes.Add(
                        new ResourceNodeDefinitionJson
                        {
                            Id = d.NodeDefId,
                            DisplayName = d.DisplayName,
                            GatherLens = d.GatherLens,
                            MaxGathers = d.MaxGathers,
                            Yield = new ResourceNodeYieldJson
                            {
                                ItemId = yieldRow.ItemId,
                                Quantity = yieldRow.Quantity,
                            },
                        });
                }

                return Results.Json(
                    new ResourceNodeDefinitionsListResponse
                    {
                        SchemaVersion = ResourceNodeDefinitionsListResponse.CurrentSchemaVersion,
                        Nodes = nodes,
                    });
            });

        return app;
    }
}
