using Femto.Common.Infrastructure;
using Femto.Modules.Media.Data;
using Femto.Modules.Media.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Femto.Modules.Media.Application;

public static class MediaStartup
{
    public static void InitializeMediaModule(this IServiceCollection rootContainer, string connectionString, string storageRoot)
    {
        var hostBuilder = Host.CreateDefaultBuilder();

        hostBuilder.ConfigureServices(services =>
        {
            services.AddDbContext<MediaContext>(builder =>
            {
                builder.UseNpgsql(connectionString);
                builder.UseSnakeCaseNamingConvention();
                var loggerFactory = LoggerFactory.Create(b => { });
                builder.UseLoggerFactory(loggerFactory);
            });
            services.AddTransient<IStorageProvider>(s => new FilesystemStorageProvider(storageRoot));
            services.AddMediatR(c => c.RegisterServicesFromAssembly(typeof(MediaStartup).Assembly));
            services.ConfigureDomainServices<MediaContext>();
        });
        
        var host = hostBuilder.Build();
        
        rootContainer.AddTransient<IMediaModule>(_ => new MediaModule(host));
        rootContainer.AddHostedService(services => new MediaApplication(host));
    }
}
