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
{
///
/// A repository for managing entities in a MongoDB data store.
/// This class extends the generic base class and implements
/// the contract to provide persistence operations for pump observation data.
///
/// The type of the entity managed by this repository.
///
/// As a specialized repository inheriting from , this class
/// reuses the base MongoDB storage capabilities while exposing the pump observation-specific repository contract.
///
public class PumpObservationRepository : MongoRepository, IPumpObservationRepository
{
private readonly ApiSettings _apiSettings;
public PumpObservationRepository(IOptions apiSettings, IMongoDatabase database) : base(database)
{
_apiSettings = apiSettings.Value;
}
///
/// Retrieves the collection name used for pump observations, returning the configured value from API settings if available, or falling back to the default "pump_observations" name when no custom configuration is provided.
///
/// The configured pump observations collection name from API settings, or the default "pump_observations" string if the setting is null.
public override string GetCollectionName()
{
return _apiSettings.PumpObservations ?? "pump_observations";
}
public override async Task CreateIndexes()
{
var indexModels = new List>
{
// Timeline por bomba (consulta más frecuente)
new CreateIndexModel(
Builders.IndexKeys
.Ascending(x => x.DeviceId)
.Descending(x => x.Time),
new CreateIndexOptions { Name = "ix_deviceId_time" }),
// consultas por paciente
new CreateIndexModel(
Builders.IndexKeys.Ascending(x => x.PatientId),
new CreateIndexOptions { Name = "ix_patientId" }),
// TTL por antigüedad (si aplica retención directa en Mongo)
// new CreateIndexModel(
// Builders.IndexKeys.Ascending(x => x.Time),
// new CreateIndexOptions { Name = "ttl_time", ExpireAfter = TimeSpan.FromDays(180) })
};
await Collection.Indexes.CreateManyAsync(indexModels);
}
///
/// Asynchronously inserts a pump observation into the underlying collection.
///
/// The pump observation document to be persisted.
public async Task InsertAsync(PumpObservation obs)
{
await Collection.InsertOneAsync(obs);
}
///
/// Inserts a batch of pump observations into the underlying collection in a single operation. Returns immediately when the input is null or contains no elements, performing no insertion in those cases.
///
/// The pump observations to insert. A null or empty collection results in a no-op.
public async Task InsertManyAsync(IEnumerable? observations)
{
if (observations == null) return;
var list = observations as IList ?? observations.ToList();
if (list.Count == 0) return;
await Collection.InsertManyAsync(list);
}
///
/// Retrieves pump observations for a specific device, optionally filtered by a time range and limited to a maximum number of results, sorted by time in descending order.
///
/// The identifier of the device whose observations should be retrieved.
/// Optional start timestamp; when provided, only observations with a time greater than or equal to this value are returned.
/// Optional end timestamp; when provided, only observations with a time less than or equal to this value are returned.
/// Optional maximum number of observations to return; when not provided, all matching observations are returned.
/// A task that represents the asynchronous operation, containing the collection of matching records.
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 query = Collection.Find(filter)
.SortByDescending(x => x.Time);
if (limit.HasValue)
query = query.Limit(limit.Value) as IOrderedFindFluent;
return await query.ToListAsync();
}
// histórico por paciente
///
/// Retrieves pump observations for a specific patient, optionally filtered by a time range and optionally capped to a maximum number of results. Results are ordered from most recent to oldest by observation time.
///
/// The identifier of the patient whose pump observations should be retrieved.
/// Optional inclusive lower bound for the observation time. When null, no lower time bound is applied.
/// Optional inclusive upper bound for the observation time. When null, no upper time bound is applied.
/// Optional maximum number of observations to return. When null, all matching observations are returned.
/// A task that represents the asynchronous operation. The task result contains the matching pump observations sorted by time in descending order.
public async Task> FindByPatientAsync(
ObjectId patientId,
DateTime? from = null,
DateTime? to = null,
int? limit = null)
{
var filter = Builders.Filter.Eq(x => x.PatientId, patientId);
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 query = Collection.Find(filter)
.SortByDescending(x => x.Time);
if (limit.HasValue)
query = query.Limit(limit.Value) as IOrderedFindFluent;
return await query.ToListAsync();
}
public async Task> FindAllLastPatientObservationTimeAsync()
{
// Pipeline:
// 1) Filtrar observaciones con PatientId no nulo
// 2) Agrupar por PatientId
// 3) Obtener el máximo Time
// 4) Devolver diccionario
var pipeline = new[]
{
new BsonDocument("$match", new BsonDocument
{
{ "patientid", new BsonDocument("$ne", BsonNull.Value) }
}),
new BsonDocument("$group", new BsonDocument
{
{ "_id", "$patientid" },
{ "LastTime", new BsonDocument("$max", "$time") }
})
};
var docs = await Collection.Aggregate(pipeline).ToListAsync();
var result = new Dictionary();
foreach (var doc in docs.Where(doc =>
doc["_id"].IsObjectId && doc["LastTime"].IsValidDateTime
))
{
result[doc["_id"].AsObjectId] = doc["LastTime"].ToUniversalTime();
}
return result;
}
///
/// Retrieves the most recent pump observation associated with the specified device identifier by querying the collection, filtering by device, and returning the observation with the latest timestamp. Returns null when no matching observation exists for the device.
///
/// The unique identifier of the device whose latest pump observation should be retrieved.
/// A task that resolves to the most recent for the device, or null if no observation is found.
public async Task FindLastByDeviceIdAsync(string deviceId)
{
return await Collection
.Find(x => x.DeviceId == deviceId)
.SortByDescending(x => x.Time)
.FirstOrDefaultAsync();
}
///
/// Retrieves all pump observations associated with the specified patient identifier.
///
/// The optional patient identifier used to filter the pump observations.
/// A task that represents the asynchronous operation, containing a collection of pump observations matching the given patient identifier.
public async Task> FindByPatientId(ObjectId? patientId)
{
return await Collection.Find(x => x.PatientId == patientId).ToListAsync();
}
///
/// Retrieves the most recent pump observations for a specified patient, deduplicated by code and name, and sorted by time in descending order.
///
/// The identifier of the patient whose observations are being retrieved.
/// The maximum number of observations to consider before deduplication. Defaults to 100.
/// A task that represents the asynchronous operation. The task result contains a list of distinct entries for the patient, ordered from most recent to oldest.
public async Task> AggregatedPatientLastObservations(ObjectId patientId, int num = 100)
{
var filterBuilder = Builders.Filter;
var sortBuilder = Builders.Sort;
var filter = filterBuilder.Eq(o => o.PatientId, patientId);
var sort = sortBuilder.Descending("time");
var options = new FindOptions { Sort = sort, Limit = num };
var result = await Collection.FindAsync(filter, options);
var observations = await result.ToListAsync();
var distinctObservations = observations.DistinctBy(m => new { m.Code, m.Name }).ToList();
var sortedObservations = distinctObservations.OrderByDescending(x => x.Time).ToList();
return sortedObservations;
}
///
/// Deletes all records whose PatientId matches the specified patient identifier.
///
/// The patient identifier whose associated records should be removed; may be null.
public async Task DeleteByPatientId(ObjectId? patientId)
{
await Collection.DeleteManyAsync(x => x.PatientId == patientId);
}
///
/// Deletes documents whose timestamp is older than the specified number of days, optionally filtered by name.
/// When is provided, only observations matching that name are removed; otherwise, all observations older than the cutoff are deleted.
/// The cutoff date is computed using UTC time.
///
/// The age threshold in days. Observations with a Time older than DateTime.UtcNow - days are eligible for deletion.
/// Optional name used to further restrict the deletion to observations with a matching Name value. If null or empty, the name filter is not applied.
/// The number of documents that were deleted.
public async Task DeleteOlderThanDaysAsync(int days, string? name = null)
{
var limitDate = DateTime.UtcNow.AddDays(-days);
var filter = Builders.Filter.Lt(x => x.Time, limitDate);
if(!string.IsNullOrEmpty(name))
filter &= Builders.Filter.Eq(x=> x.Name, name);
return (await Collection.DeleteManyAsync(filter)).DeletedCount;
}
///
/// Deletes older pump observations while retaining only the most recent records for each device.
/// Devices whose observation count is less than or equal to the threshold are left untouched.
///
/// The maximum number of most recent records to keep per device.
/// The total number of observations deleted across all devices.
public async Task DeleteKeepLastNAsync(int maxCount)
{
// Para cada DeviceId:
var deviceIds = await Collection
.Distinct("DeviceId", FilterDefinition.Empty)
.ToListAsync();
long totalDeleted = 0;
foreach (var filter in deviceIds.Select(deviceId =>
Builders.Filter.Eq(x => x.DeviceId, deviceId)
))
{
var all = await Collection.Find(filter)
.SortByDescending(x => x.Time)
.ToListAsync();
if (all.Count <= maxCount)
continue;
var toDelete = all.Skip(maxCount).Select(x => x.Id).ToList();
var deleteFilter = Builders.Filter.In(x => x.Id, toDelete);
var result = await Collection.DeleteManyAsync(deleteFilter);
totalDeleted += result.DeletedCount;
}
return totalDeleted;
}
///
/// Updates the specified field in multiple documents, setting it to a new where it currently matches the optional old .
///
/// The name of the field to update. Must not be null or empty.
/// The new value to assign to the field.
/// The current value used to match documents; if null, the filter matches documents where the field is null.
/// The number of documents that were modified by the update operation.
/// Thrown when is null, empty, or whitespace.
public async Task UpdateManyObjectIdByFieldAsync(string fieldName, ObjectId newId, ObjectId? oldId)
{
if (string.IsNullOrWhiteSpace(fieldName))
throw new ArgumentException("fieldName can't be null or empty.", nameof(fieldName));
// Normalize casing (Mongo is case-sensitive)
// if (fieldName.Equals("patientid", StringComparison.OrdinalIgnoreCase))
// fieldName = nameof(PumpObservation.PatientId);
var filter = Builders.Filter.Eq(fieldName, oldId);
var update = Builders.Update.Set(fieldName, newId);
var result = await Collection.UpdateManyAsync(filter, update);
return result.ModifiedCount;
}
public async Task DeleteOlderNumberAsync(string name, int maxCount)
{
if (string.IsNullOrWhiteSpace(name))
return 0;
// 1. Filtrar todas las observaciones con ese Name
var filter = Builders.Filter.Eq(x => x.Name, name);
// 2. Obtenerlas ordenadas por Time DESC (las más recientes primero)
var all = await Collection
.Find(filter)
.SortByDescending(x => x.Time)
.ToListAsync();
// 3. Si hay menos o igual al número permitido → no borrar nada
if (all.Count <= maxCount)
return 0;
// 4. Seleccionar TODAS excepto las maxCount más recientes
var toDeleteIds = all
.Skip(maxCount)
.Select(x => x.Id)
.ToList();
if (toDeleteIds.Count == 0)
return 0;
// 5. Borrar las seleccionadas
var deleteFilter = Builders.Filter.In(x => x.Id, toDeleteIds);
var result = await Collection.DeleteManyAsync(deleteFilter);
return result.DeletedCount;
}
///
/// Retrieves up to the two most recent pump observations for the specified patient and observation name, ordered by time descending. Returns an empty list if the name is null, empty, or whitespace.
///
/// The unique identifier of the patient whose observations are being queried.
/// The name of the pump observation to filter by. If null, empty, or whitespace, an empty list is returned.
/// A task representing the asynchronous operation, containing a list of the matching pump observations (at most two) sorted from newest to oldest.
public async Task> FindLastObservations(ObjectId patientId, string name)
{
if (string.IsNullOrWhiteSpace(name))
return [];
var filter = Builders.Filter.And(
Builders.Filter.Eq(x => x.PatientId, patientId),
Builders.Filter.Eq(x => x.Name, name)
);
return await Collection
.Find(filter)
.SortByDescending(x => x.Time)
.Limit(2)
.ToListAsync();
}
}
}