using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
namespace adas_core.Infrastructure.Repositories;
///
/// Provides a MongoDB-backed repository for persisting and retrieving archived patient treatment records.
/// Inherits from and implements the contract.
///
public class TreatmentArchiveRepository : MongoRepository, ITreatmentArchiveRepository
{
private readonly ApiSettings _apiSettings;
public TreatmentArchiveRepository(IOptions apiSettings, IMongoDatabase database) : base(database)
{
if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
_apiSettings = apiSettings.Value;
} //For testing
///
/// Asynchronously inserts a single document into the collection.
///
/// The patient treatment entity to persist.
public override async Task InsertOneAsync(PatientTreatment patientTreatment)
{
await Collection.InsertOneAsync(patientTreatment);
}
///
/// Deletes all patient treatments whose order time is before the specified date.
///
/// The cutoff date; treatments with an order time earlier than this are removed.
public async Task DeleteBeforeDate(DateTime date)
{
var filter = Builders.Filter.Lt(po => po.OrderTime, date);
await Collection.DeleteManyAsync(filter);
}
///
/// Inserts a batch of records into the underlying collection using a bulk write operation and returns the number of documents that were successfully inserted.
///
/// The collection of patient treatment records to insert into the database.
/// The total count of patient treatment records inserted by the bulk write operation.
public async Task InsertBatch(IEnumerable treatments)
{
var writes = new List>();
writes.AddRange(treatments.Select(d => new InsertOneModel(d)));
var bulkInsert = await Collection.BulkWriteAsync(writes);
return bulkInsert.InsertedCount;
}
///
/// Retrieves all patient treatment records associated with the specified patient identifier from the collection.
///
/// The unique identifier of the patient whose treatment records are to be retrieved.
/// A task that represents the asynchronous operation, containing a list of records matching the specified patient.
public async Task> FindAllFromPatient(ObjectId patientId)
{
var filter = Builders.Filter.Eq(t => t.PatientId, patientId);
var result = await Collection.FindAsync(filter);
return await result.ToListAsync();
}
///
/// Retrieves the collection name for archive patients treatments, falling back to the default "archive_patients_treatments" value when the API settings do not specify one.
///
/// The configured collection name from the API settings, or the default "archive_patients_treatments" if the setting is null.
public override string GetCollectionName()
{
return _apiSettings.ArchivePatientsTreatments ?? "archive_patients_treatments";
}
}