using Knot.Contracts.Profiles.Domain;
using Knot.Modules.Profiles.Infrastructure.Database;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;

namespace Knot.Modules.Profiles;

public static class DependencyInjection
{
    public static IServiceCollection AddProfilesModule(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddScoped<Knot.Contracts.Profiles.Domain.IProfileRepository, ProfileRepository>();
        services.AddScoped<Knot.Contracts.Profiles.Domain.IProfilesUnitOfWork, ProfilesUnitOfWork>();
        services.AddScoped<Knot.Contracts.Profiles.Domain.IAvatarStorageService, AvatarStorageService>();

        // MongoDB Registration
        var mongoConnection = configuration.GetConnectionString("MongoConnection")
                             ?? configuration["MONGO_URL"]
                             ?? "mongodb://mongo:27017";

        var mongoClient = new MongoClient(mongoConnection);
        var databaseName = new MongoUrl(mongoConnection).DatabaseName ?? "knot_messager";
        var database = mongoClient.GetDatabase(databaseName);
        services.AddSingleton<IMongoDatabase>(database);

        services.AddMediatR(config =>
            config.RegisterServicesFromAssembly(typeof(DependencyInjection).Assembly));

        return services;
    }
}
