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;

/// <summary>
/// Provides a MongoDB-backed repository for persisting and retrieving archived patient treatment records.
/// Inherits from <see cref="MongoRepository{PatientTreatment}"/> and implements the <see cref="ITreatmentArchiveRepository"/> contract.
/// </summary>
public class TreatmentArchiveRepository : MongoRepository<PatientTreatment>, ITreatmentArchiveRepository
{
    private readonly ApiSettings _apiSettings;

    public TreatmentArchiveRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database) : base(database)
    {
        if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
        _apiSettings = apiSettings.Value;
    } //For testing

  

    /// <summary>
    /// Asynchronously inserts a single <see cref="PatientTreatment"/> document into the collection.
    /// </summary>
    /// <param name="patientTreatment">The patient treatment entity to persist.</param>
    public override async Task InsertOneAsync(PatientTreatment patientTreatment)
        {
            await Collection.InsertOneAsync(patientTreatment);
        }

    /// <summary>
    /// Deletes all patient treatments whose order time is before the specified date.
    /// </summary>
    /// <param name="date">The cutoff date; treatments with an order time earlier than this are removed.</param>
    public async Task DeleteBeforeDate(DateTime date)
        {
            var filter = Builders<PatientTreatment>.Filter.Lt(po => po.OrderTime, date);
            await Collection.DeleteManyAsync(filter);
        }

    /// <summary>
    /// Inserts a batch of <see cref="PatientTreatment"/> records into the underlying collection using a bulk write operation and returns the number of documents that were successfully inserted.
    /// </summary>
    /// <param name="treatments">The collection of patient treatment records to insert into the database.</param>
    /// <returns>The total count of patient treatment records inserted by the bulk write operation.</returns>
    public async Task<long> InsertBatch(IEnumerable<PatientTreatment> treatments)
        {
            var writes = new List<WriteModel<PatientTreatment>>();
            writes.AddRange(treatments.Select(d => new InsertOneModel<PatientTreatment>(d)));
    
            var bulkInsert = await Collection.BulkWriteAsync(writes);
    
            return bulkInsert.InsertedCount;
        }

    /// <summary>
    /// Retrieves all patient treatment records associated with the specified patient identifier from the collection.
    /// </summary>
    /// <param name="patientId">The unique identifier of the patient whose treatment records are to be retrieved.</param>
    /// <returns>A task that represents the asynchronous operation, containing a list of <see cref="PatientTreatment"/> records matching the specified patient.</returns>
    public async Task<List<PatientTreatment>> FindAllFromPatient(ObjectId patientId)
        {
            var filter = Builders<PatientTreatment>.Filter.Eq(t => t.PatientId, patientId);
            var result = await Collection.FindAsync(filter);
    
            return await result.ToListAsync();
        }

    /// <summary>
    /// 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.
    /// </summary>
    /// <returns>The configured collection name from the API settings, or the default "archive_patients_treatments" if the setting is null.</returns>
    public override string GetCollectionName()
        {
            return _apiSettings.ArchivePatientsTreatments ?? "archive_patients_treatments";
        }
}