using Application.Services.Database;
using MongoDB.Driver;
using MongoDB.Bson;

namespace Infrastructure.Services.MongoDB
{
    public class MongoDbService
    {
        private readonly IMongoClient _database;
        private readonly string _databaseName;
        private readonly string _collectionName;

        public MongoDbService(string connectionString, string databaseName, string collectionName)
        {
            _databaseName = databaseName;
            _collectionName = collectionName;

            Console.WriteLine($"Connection string: {connectionString}");
            Console.WriteLine($"Database Name: {databaseName}");
            Console.WriteLine($"Collection Name: {collectionName}");

            var settings = MongoClientSettings.FromConnectionString(connectionString);
            settings.ServerApi = new ServerApi(ServerApiVersion.V1);
            _database = new MongoClient(settings);

            try
            {
                var result = _database.GetDatabase("admin").RunCommand<BsonDocument>(new BsonDocument("ping", 1));
                Console.WriteLine("Pinged your deployment. You successfully connected to MongoDB!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public IMongoCollection<T> GetCollection<T>()
        {
            return _database.GetDatabase(_databaseName).GetCollection<T>(_collectionName);
        }

        public async Task<List<T>> FindAsync<T>(List<(string FieldName, string Value)> criteria)
        {
            var collection = _database.GetDatabase(_databaseName).GetCollection<T>(_collectionName);

            var filters = new List<FilterDefinition<T>>();
            foreach (var (FieldName, Value) in criteria) filters.Add(Builders<T>.Filter.Eq(FieldName, Value));

            var combinedFilter = Builders<T>.Filter.And(filters);

            return await collection.Find(combinedFilter).ToListAsync();
        }

        public async Task AddAsync<T>(T document)
        {
            var collection = _database.GetDatabase(_databaseName).GetCollection<T>(_collectionName);
            await collection.InsertOneAsync(document);
        }

        public async Task ModifyAsync<T>(string keyField, string keyValue, T document)
        {
            var collection = _database.GetDatabase(_databaseName).GetCollection<T>(_collectionName);
            var filter = Builders<T>.Filter.Eq(keyField, keyValue);
            await collection.ReplaceOneAsync(filter, document, new ReplaceOptions { IsUpsert = true });
        }

        public async Task DeleteAsync<T>(string keyField, string keyValue)
        {
            var collection = _database.GetDatabase(_databaseName).GetCollection<T>(_collectionName);
            var filter = Builders<T>.Filter.Eq(keyField, keyValue);
            await collection.DeleteOneAsync(filter);
        }
    }
}