using Autofac;
using eSuite.Core.Clock;
using Microsoft.Extensions.Configuration;

using System.Reflection;

namespace e_suite.DependencyInjection;

public sealed class ModuleConfig
{
    public List<string> Modules { get; set; } = new();
}

public class ESuiteModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        base.Load(builder);
        builder.RegisterType<UtcClock>().As<IClock>().SingleInstance();
            
        RegisterAllModuleIocRegistrations(builder);
    }

    protected static void RegisterAllModuleIocRegistrations(ContainerBuilder builder)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
            .Build();

        var moduleConfig = configuration.Get<ModuleConfig>();

        var basePath = AppContext.BaseDirectory;
        var assemblies = new List<Assembly>();

        foreach (var module in moduleConfig.Modules)
        {
            var fullPath = Path.Combine(basePath, module);

            if (!File.Exists(fullPath))
                throw new FileNotFoundException($"Configured module not found: {fullPath}");

            assemblies.Add(Assembly.LoadFrom(fullPath));
        }

        var registrationTypes = assemblies
            .SelectMany(a => a.GetTypes())
            .Where(t => typeof(IIocRegistration).IsAssignableFrom(t)
                        && !t.IsAbstract
                        && !t.IsInterface).ToList();

        foreach (var type in registrationTypes)
        {
            var instance = (IIocRegistration)Activator.CreateInstance(type)!;
            instance.RegisterTypes(builder);
        }
    }

}