using Microsoft.Extensions.Logging; using MongoDB.Driver; using Shared.Core.Entities; using Shared.Core.Exceptions; using Shared.Core.Interfaces.SPI; using Shared.Core.Shared.Models; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace Shared.Infrastructure.Services.Mongo { public class MongoItemInfra : IItemInfra where T : BaseEntity { public readonly IMongoCollection _dbSet; public readonly ILogger> _logger; public MongoItemInfra( IMongoDatabase database, ILogger> logger) { _dbSet = database.GetCollection(typeof(T).Name.ToLower()); _logger = logger; } public async Task AddItemAsync(T item) { try { await _dbSet.InsertOneAsync(item); } catch (Exception ex) { _logger.LogError(ex, "Error while adding an item."); throw Errors.CannotQueryError; } } public async Task DeleteItemsAsync(List ids) { try { // Build a filter to match all the IDs in the list var filter = Builders.Filter.In("Id", ids); // Delete all matching documents var result = await _dbSet.DeleteManyAsync(filter); _logger.LogInformation($"Deleted {result.DeletedCount} items with the provided IDs."); } catch (Exception ex) { _logger.LogError(ex, $"Error while deleting items with IDs: {string.Join(", ", ids)}"); throw Errors.CannotQueryError; } } public async Task GetItemByIdAsync(Guid id, params Expression>[] includes) { try { return await _dbSet.Find(Builders.Filter.Eq("Id", id)).FirstOrDefaultAsync(); } catch (Exception ex) { _logger.LogError(ex, $"Error while fetching item with Id {id}"); throw Errors.CannotQueryError; } } public async Task> GetItemsAsync( PagingParams pagingParams, params Expression>[] includes) { try { int skipValues = (pagingParams.Page - 1) * pagingParams.Per_Page; var filter = Builders.Filter.Empty; var totalRecords = await _dbSet.CountDocumentsAsync(filter); var items = await _dbSet .Find(filter) .Sort(Builders.Sort.Descending("Id")) // Sort by descending Id, adjust field as needed .Skip(skipValues) .Limit(pagingParams.Per_Page) .ToListAsync(); return new PagerData { Items = items, TotalRecords = (int)totalRecords }; } catch (Exception ex) { // You can add logging here if needed throw Errors.CannotQueryError; } } public async Task UpdateItemAsync(T item) { try { var id = typeof(T).GetProperty("Id")?.GetValue(item); if (id == null) throw Errors.CannotFindTheItem; await _dbSet.ReplaceOneAsync(Builders.Filter.Eq("Id", id), item); } catch (Exception ex) { _logger.LogError(ex, "Error while updating an item."); throw Errors.CannotQueryError; } } } }