using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Pumps;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
namespace adas_core.Infrastructure.Repositories;
///
/// Represents a MongoDB-backed repository for documents, exposing pump alarm event-specific data access through the contract.
///
///
/// Inherits the generic MongoDB persistence capabilities of , specializing them for the entity type.
///
public class PumpAlarmEventRepository : MongoRepository, IPumpAlarmEventRepository
{
private readonly ApiSettings _apiSettings;
public PumpAlarmEventRepository(IOptions apiSettings, IMongoDatabase database)
: base(database)
{
_apiSettings = apiSettings.Value;
}
public override string GetCollectionName()
{
return _apiSettings.PumpAlarmEvent ?? "pump_alarm_event";
}
public override async Task CreateIndexes()
{
var indexModels = new List>
{
// Principal para consultas por bomba y orden temporal
new(
Builders.IndexKeys
.Ascending(x => x.DeviceId)
.Descending(x => x.Time),
new CreateIndexOptions { Name = "ix_deviceId_time" }),
// Índice temporal
new(
Builders.IndexKeys.Descending(x => x.Time),
new CreateIndexOptions { Name = "ix_time" }),
// por paciente
new(
Builders.IndexKeys.Ascending(x => x.PatientId),
new CreateIndexOptions { Name = "ix_patientId" }),
//por tipo de alarma dentro de una bomba
new(
Builders.IndexKeys
.Ascending(x => x.DeviceId)
.Ascending(x => x.AlarmType),
new CreateIndexOptions { Name = "ix_device_alarmType" })
};
await Collection.Indexes.CreateManyAsync(indexModels);
}
public async Task InsertAsync(PumpAlarmEvent alarmEvent)
{
await Collection.InsertOneAsync(alarmEvent);
}
public async Task> FindByDeviceIdAsync(string deviceId, DateTime? from = null,
DateTime? to = null, int? limit = null)
{
var filter = Builders.Filter.Eq(x => x.DeviceId, deviceId);
if (from.HasValue)
filter &= Builders.Filter.Gte(x => x.Time, from.Value);
if (to.HasValue)
filter &= Builders.Filter.Lte(x => x.Time, to.Value);
var find = Collection.Find(filter).SortByDescending(x => x.Time);
if (limit.HasValue) find = find.Limit(limit.Value) as IOrderedFindFluent;
return await find.ToListAsync();
}
public async Task FindLastByDeviceIdAsync(string deviceId)
{
return await Collection
.Find(x => x.DeviceId == deviceId)
.SortByDescending(x => x.Time)
.FirstOrDefaultAsync();
}
public async Task DeleteByPatientId(ObjectId patientId)
{
await Collection.DeleteManyAsync(x => x.PatientId == patientId);
}
public async Task UpdateManyObjectIdByFiledNameAsync(string fieldName, ObjectId newId, ObjectId oldId)
{
var filter = Builders.Filter.Eq(fieldName, oldId);
var update = Builders.Update.Set(fieldName, newId);
var result = await Collection.UpdateManyAsync(filter, update);
return result.ModifiedCount;
}
}