using Diligent.WebAPI.Business.Interfaces;
using Diligent.WebAPI.Data;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Diligent.WebAPI.Business.Services
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
    {
        protected readonly IMongoDBContext _mongoContext;
        protected IMongoCollection<TEntity> _dbCollection;
        private readonly FilterDefinitionBuilder<TEntity> _builder = Builders<TEntity>.Filter;

        public BaseRepository(IMongoDBContext context)
        {
            _mongoContext = context;
            _dbCollection = _mongoContext.GetCollection<TEntity>(typeof(TEntity).Name);
        }

        public async Task<List<TEntity>> GetAsync()
        {
            var all = await _dbCollection.FindAsync(_builder.Empty);
            return await all.ToListAsync();
        }
        public async Task<TEntity> GetByIdAsync(string id)
        {
            var element = await _dbCollection.FindAsync(_builder.Eq("_id", new ObjectId(id)));
            return await element.FirstOrDefaultAsync();
        }
        public async Task RemoveAsync(string id)
        {
            await _dbCollection.FindOneAndDeleteAsync(_builder.Eq("_id", new ObjectId(id)));
        }
        public async Task UpdateAsync(string id, TEntity updateEntity)
        {
            await _dbCollection.FindOneAndReplaceAsync(_builder.Eq("_id", new ObjectId(id)), updateEntity);
        }
        public async Task CreateAsync(TEntity entity)
        {
            await _dbCollection.InsertOneAsync(entity);
        }
    }
}
