using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using NeonSprawl.Server.Game.Skills;

namespace NeonSprawl.Server.Game.Items;

/// <summary>DI registration for the fail-fast item catalog (NEO-51).</summary>
public static class ItemCatalogServiceCollectionExtensions
{
    /// <summary>Binds <see cref="ContentPathsOptions"/> and registers <see cref="ItemDefinitionCatalog"/> as a singleton.</summary>
    public static IServiceCollection AddItemDefinitionCatalog(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddOptions<ContentPathsOptions>()
            .Bind(configuration.GetSection(ContentPathsOptions.SectionName));

        services.AddSingleton<ItemDefinitionCatalog>(sp =>
        {
            var hostEnv = sp.GetRequiredService<IHostEnvironment>();
            var opts = sp.GetRequiredService<IOptions<ContentPathsOptions>>().Value;
            var logger = sp.GetRequiredService<ILoggerFactory>()
                .CreateLogger("NeonSprawl.Server.Game.Items.ItemCatalog");

            var itemsDir = ItemCatalogPathResolution.ResolveItemsDirectory(opts.ItemsDirectory, hostEnv.ContentRootPath);
            var schemaPath = ItemCatalogPathResolution.ResolveItemDefSchemaPath(
                itemsDir,
                opts.ItemDefSchemaPath,
                hostEnv.ContentRootPath);

            return ItemDefinitionCatalogLoader.Load(itemsDir, schemaPath, logger);
        });

        return services;
    }
}
