using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoUtils = adas_core.Infrastructure.Utils.MongoUtils;
namespace adas_core.Infrastructure.Repositories;
///
/// Repository for managing patient appointments in a MongoDB database.
/// This class provides methods to perform CRUD operations and queries related to patient appointments, such as retrieving appointments by patient ID, finding appointments by point of care, and updating or deleting appointments.
/// It utilizes the MongoDB driver for database interactions and is configured using application settings for collection names and other parameters.
///
public class AppointmentRepository : MongoRepository, IAppointmentRepository
{
///
/// Holds the API settings for the repository, including collection names and other configuration parameters.
///
private readonly ApiSettings _apiSettings;
///
/// Initializes a new instance of the class with the specified API settings and MongoDB database.
///
/// The API settings containing configuration for the repository.
/// The MongoDB database instance.
/// Thrown when any of the input parameters are null.
public AppointmentRepository(
IOptions apiSettings,
IMongoDatabase database) : base(database)
{
if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
_apiSettings = apiSettings.Value;
} //For testing
///
/// Gets the name of the MongoDB collection for patient appointments. This method retrieves the collection name from the API settings, allowing for flexible configuration.
/// If the collection name is not specified in the settings, it defaults to "patients_appointments".
///
/// The name of the MongoDB collection for patient appointments.
public override string GetCollectionName()
{
return _apiSettings.PatientsAppointments ?? "patients_appointments";
}
///
/// Retrieves a list of patient appointments for a given patient ID. This method constructs a filter to query the MongoDB collection based on the patient ID and sorts the results by creation time in descending order.
///
/// The ID of the patient whose appointments are to be retrieved.
/// A list of patient appointments for the specified patient ID.
public async Task> GetByPatient(ObjectId patientId)
{
var filter = Builders.Filter.Eq(ob => ob.PatientId, patientId);
var options = new FindOptions
{
Sort = Builders.Sort.Descending("createTime")
};
var result = await Collection.FindAsync(filter, options);
return result.ToList();
}
///
/// Finds patient appointments based on a given point of care (PoC). This method constructs a filter to query the MongoDB collection for appointments that match the specified point of care, which includes details such as bed, room, and unit name. It utilizes the FindByLocation method to perform the actual query based on the constructed patient location.
///
/// The point of care details to filter appointments.
/// A list of patient appointments that match the specified point of care.
public async Task> FindByPoC(PointOfCare poc)
{
var location = new PatientLocation()
{
Bed = poc.Bed,
Room = poc.Room,
UnitName = poc.UnitName
};
return await FindByLocation(location);
}
///
/// Inserts a new patient appointment into the MongoDB collection. This method ensures that the creation time of the appointment is set to the current UTC time if it is not already specified before inserting the appointment into the database using the base class's InsertOneAsync method.
///
/// The patient appointment to be inserted.
/// A task representing the asynchronous operation.
public override async Task InsertOneAsync(PatientAppointment appointment)
{
appointment.CreateTime ??= DateTime.UtcNow;
await base.InsertOneAsync(appointment);
}
///
/// Updates an existing patient appointment in the MongoDB collection. This method takes a patient appointment object as input and updates the corresponding document in the database based on the appointment's ID.
/// It uses the UpdateOneAsync method from the base class to perform the update operation.
///
/// The patient appointment to be updated.
/// A task representing the asynchronous operation.
public async Task Update(PatientAppointment appointment)
{
await UpdateOneAsync(appointment.Id, appointment);
}
///
/// Deletes a patient appointment from the MongoDB collection based on the appointment's ID. This method constructs a filter to identify the document to be deleted using the appointment's ID and then calls the DeleteOneAsync method to remove the document from the database.
///
/// The ID of the patient appointment to be deleted.
/// A task representing the asynchronous operation.
public new async Task DeleteAsync(ObjectId id)
{
var filter = Builders.Filter.Eq(t => t.Id, id); // Replace 'T' with your actual class name.
await Collection.DeleteOneAsync(filter);
}
///
/// Finds patient appointments based on the patient ID. This method constructs a filter to query the MongoDB collection for appointments that match the specified patient ID and returns an asynchronous cursor to iterate through the results.
///
/// The ID of the patient whose appointments are to be retrieved.
/// An asynchronous cursor to iterate through the patient appointments.
public Task> FindByPatientIdAsync(ObjectId patientId)
{
var filter = Builders.Filter.Eq(ob => ob.PatientId, patientId);
return Collection.FindAsync(filter);
}
///
/// Deletes all patient appointments associated with a specific patient ID. This method constructs a filter to identify all documents in the MongoDB collection that match the specified patient ID and then calls the DeleteManyAsync method to remove all matching documents from the database.
///
/// The ID of the patient whose appointments are to be deleted.
/// A task representing the asynchronous operation.
public async Task DeleteByPatientId(ObjectId patientId)
{
var filter = Builders.Filter.Eq(po => po.PatientId, patientId);
await Collection.DeleteManyAsync(filter);
}
///
/// Finds a patient appointment based on the patient ID and visit number. This method constructs a filter to query the MongoDB collection for an appointment that matches both the specified patient ID and visit number, and returns the first matching appointment if found, or null if no match is found.
///
/// The ID of the patient whose appointment is to be retrieved.
/// The visit number of the appointment to be retrieved.
/// The first matching patient appointment if found, or null if no match is found.
public async Task FindByPatientAndVisitNumber(ObjectId patientId, string visitNumber)
{
var builder = Builders.Filter;
var filter = builder.And(
builder.Eq(ob => ob.PatientId, patientId),
builder.Eq(ob => ob.VisitNumber, visitNumber)
);
var result = await Collection.FindAsync(filter);
return await result.FirstOrDefaultAsync();
}
///
/// Finds a patient appointment based on the patient ID and appointment reason. This method constructs a filter to query the MongoDB collection for an appointment that matches both the specified patient ID and appointment reason, and returns the first matching appointment if found, or null if no match is found.
///
/// The ID of the patient whose appointment is to be retrieved.
/// The reason for the appointment to be retrieved.
/// The first matching patient appointment if found, or null if no match is found.
public async Task FindByPatientAndReason(ObjectId patientId, string? appointmentReason)
{
var builder = Builders.Filter;
var filter = builder.And(
builder.Eq(ob => ob.PatientId, patientId),
builder.Eq(ob => ob.AppointmentReason, appointmentReason)
);
var result = await Collection.FindAsync(filter);
return await result.FirstOrDefaultAsync();
}
///
/// Finds patient appointments based on a given patient location. This method constructs a filter to query the MongoDB collection for appointments that match the specified patient location, which includes details such as bed, room, and unit name. It uses the Builders class to create a filter that checks for the existence of the Locations field and matches the specified location details within the ResourceGroups of the appointments.
///
/// The location details to filter patient appointments by.
/// A list of patient appointments that match the specified location.
public async Task> FindByLocation(PatientLocation location)
{
var builder = Builders.Filter;
var existsFilter = builder.Exists(rg => rg.Locations);
var locationFilter = builder.ElemMatch(rg => rg.Locations,
l => l.Bed == location.Bed && l.UnitName == location.UnitName);
var combinedFilter = builder.And(existsFilter, locationFilter);
var filter = Builders.Filter.ElemMatch(pa => pa.ResourceGroups, combinedFilter);
var result = await Collection.FindAsync(filter);
return result?.ToList()??[];
}
///
/// Updates the ObjectId references in patient appointments when a patient's ID changes. This method constructs a filter to identify all documents in the MongoDB collection that match the specified old patient ID and then updates those documents to reference the new patient ID using the UpdateManyAsync method.
///
/// The name ID associated with the patient appointments to be updated.
/// The new ObjectId to replace the old patient ID.
/// The old ObjectId of the patient whose appointments are to be updated.
/// A task representing the asynchronous operation.
public async Task UpdateManyObjectId(string nameId, ObjectId id, ObjectId oldId)
{
await UpdateManyObjectIdAsync(nameId, id, oldId);
}
///
/// Creates indexes for the patient appointments collection in MongoDB. This method defines a list of indexes to be created, including an index on the patient ID field, and then calls the EnsureIndexes method from the MongoUtils class to ensure that the specified indexes are created in the database.
/// The indexes are created in the background and are not unique.
///
/// A task representing the asynchronous operation.
public override async Task CreateIndexes()
{
var options = new CreateIndexOptions { Background = true, Unique = false };
var indexes = new List>
{
new("{ patientid: 1 }", options)
};
await MongoUtils.EnsureIndexes(Collection, indexes);
}
}