
using audit_logs.Models.AppSettings;
using MongoDB.Driver;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;

namespace audit_logs.Utils;

public static class MongoDbHostBuilderExtension
{
    #region MongoDB
    private static MongoDB.Driver.MongoClient? _mongoClient;
    private static IMongoDatabase? _mongoDb;
    #endregion
    public static IHostBuilder UseMongo(this IHostBuilder hostBuilder)
    {
        ConfigureMongoDbConventions();

       // ConfigureRegisterMapClass();

        return hostBuilder;
    }
    public static IMongoDatabase GetMongoDB(IOptions<MongoDbSettingsAudit> dbSettings)
    {
        _mongoDb ??= ConfigureMongoDbConnection(dbSettings);
        return _mongoDb;
    }
    private static IMongoDatabase ConfigureMongoDbConnection(IOptions<MongoDbSettingsAudit> dbSettings)
    {
        var connectionString = dbSettings.Value.ConnectionString;
            
        var databaseName = dbSettings.Value.DatabaseName;
            
        if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(databaseName))
        {
            throw new Exception("DataBase connection string and name is requiered");
        }

        _mongoClient = new MongoDB.Driver.MongoClient(connectionString);

        var mongoDb = _mongoClient.GetDatabase(databaseName);
        return mongoDb;
    }
    public static void ConfigureMongoDbConventions()
    {
        var _pack = new ConventionPack
        {
            new IgnoreExtraElementsConvention(true),
            new CamelCaseElementNameConvention()
        };

        ConventionRegistry.Register(
            "Ignore Extra Elements Convention",
            _pack,
            t => true);

        ConventionRegistry.Register(
            "Camel Case Convention",
            _pack,
            t => true);
    }
    
     
    
}