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

namespace Infrastructure.Services.MongoDB;

public class MongoDbService : IMongoDbService
{
    private readonly IMongoDatabase _database;

    public MongoDbService(string connectionString)
    {
        var url = new MongoUrl(connectionString);
        var client = new MongoClient(url);
        _database = client.GetDatabase(url.DatabaseName);
    }

    public IMongoCollection<T> GetCollection<T>(string collectionName)
    {
        return _database.GetCollection<T>(collectionName);
    }

    public async Task<List<T>> FindAsync<T>(string collectionName, List<(string FieldName, string Value)> criteria)
    {
        var collection = _database.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>(string collectionName, T document)
    {
        var collection = _database.GetCollection<T>(collectionName);
        await collection.InsertOneAsync(document);
    }

    public async Task ModifyAsync<T>(string collectionName, string keyField, string keyValue, T document)
    {
        var collection = _database.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 collectionName, string keyField, string keyValue)
    {
        var collection = _database.GetCollection<T>(collectionName);
        var filter = Builders<T>.Filter.Eq(keyField, keyValue);
        await collection.DeleteOneAsync(filter);
    }
}