namespace NeonSprawl.Server.Game.Crafting;

/// <summary>Maps <c>GET /game/world/recipe-definitions</c> (NEO-68).</summary>
public static class RecipeDefinitionsWorldApi
{
    public static WebApplication MapRecipeDefinitionsWorldApi(this WebApplication app)
    {
        app.MapGet(
            "/game/world/recipe-definitions",
            (IRecipeDefinitionRegistry registry) =>
            {
                var defs = registry.GetDefinitionsInIdOrder();
                var recipes = new List<RecipeDefinitionJson>(defs.Count);
                foreach (var d in defs)
                {
                    recipes.Add(
                        new RecipeDefinitionJson
                        {
                            Id = d.Id,
                            DisplayName = d.DisplayName,
                            RecipeKind = d.RecipeKind,
                            RequiredSkillId = d.RequiredSkillId,
                            Inputs = MapIoRows(d.Inputs),
                            Outputs = MapIoRows(d.Outputs),
                        });
                }

                return Results.Json(
                    new RecipeDefinitionsListResponse
                    {
                        SchemaVersion = RecipeDefinitionsListResponse.CurrentSchemaVersion,
                        Recipes = recipes,
                    });
            });

        return app;
    }

    private static List<RecipeIoJson> MapIoRows(IReadOnlyList<RecipeIoRow> rows)
    {
        var list = new List<RecipeIoJson>(rows.Count);
        foreach (var row in rows)
        {
            list.Add(
                new RecipeIoJson
                {
                    ItemId = row.ItemId,
                    Quantity = row.Quantity,
                });
        }

        return list;
    }
}
