using Autofac;
using e_suite.Database.Core;
using e_suite.Database.SqlServer;
using e_suite.DependencyInjection;
using e_suite.MessageProcessor.Handlers;
using e_suite.MessageProcessor.QueueProcessor;
using eSuite.Core.Clock;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace e_suite.MessageProcessor.DependencyInjection;

/// <summary>
/// Used as the primary location for IOC type registration for e-suite.
/// </summary>
public class CoreRegistrationModule : ESuiteModule
{
    /// <summary>
    /// Use the builder to register all the types and interfaces that the API requires to operate properly.
    /// </summary>
    /// <param name="builder"></param>
    protected override void Load(ContainerBuilder builder)
    {
        base.Load(builder);
        
        var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder.AddConsole());
        builder.Register(x => loggerFactory.CreateLogger("e-Suite.MessageProcessor")).As<ILogger>().SingleInstance();

        builder.RegisterInstance(ESuiteDatabaseExtension.BuildConfiguration()).As<IConfiguration>().SingleInstance();
        builder.Register(c =>
            {
                var clock = c.Resolve<IClock>();
                return ESuiteDatabaseExtension.CreateDatabase(clock)
                    .GetAwaiter()
                    .GetResult();
            })
            .As<IEsuiteDatabaseDbContext>()
            .InstancePerLifetimeScope();

        builder.RegisterType<QueueProcessorService>().InstancePerLifetimeScope();
        builder.RegisterType<DatabaseQueueHandler>().InstancePerLifetimeScope();
        builder.RegisterType<SigmaImportQueueHandler>().InstancePerLifetimeScope();
        builder.RegisterType<EFlowImportQueueHandler>().InstancePerLifetimeScope();
        builder.RegisterType<ActivityQueueHandler>().InstancePerLifetimeScope();
    }
}