using System.Diagnostics.CodeAnalysis;

namespace NeonSprawl.Server.Game.Crafting;

/// <summary>Adapter over <see cref="RecipeDefinitionCatalog"/> (NEO-67).</summary>
public sealed class RecipeDefinitionRegistry(RecipeDefinitionCatalog catalog) : IRecipeDefinitionRegistry
{
    private readonly IReadOnlyList<RecipeDefRow> _definitionsInIdOrder = BuildDefinitionsInIdOrder(catalog);

    /// <inheritdoc />
    public bool TryGetDefinition(string? recipeId, [NotNullWhen(true)] out RecipeDefRow? definition)
    {
        if (recipeId is null)
        {
            definition = null;
            return false;
        }

        return catalog.TryGetRecipe(recipeId, out definition);
    }

    /// <inheritdoc />
    public IReadOnlyList<RecipeDefRow> GetDefinitionsInIdOrder() => _definitionsInIdOrder;

    private static IReadOnlyList<RecipeDefRow> BuildDefinitionsInIdOrder(RecipeDefinitionCatalog catalog)
    {
        var ids = catalog.ById.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray();
        var list = new List<RecipeDefRow>(ids.Length);
        foreach (var id in ids)
        {
            list.Add(catalog.ById[id]);
        }

        return list;
    }
}
