using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using MongoUtils = adas_core.Infrastructure.Utils.MongoUtils;

namespace adas_core.Infrastructure.Repositories;

/// <summary>
/// Repository for managing archived patient diagnoses in MongoDB. This repository provides methods for inserting, deleting, and indexing patient diagnosis records in the archive collection.
/// </summary>
public class DiagnosisArchiveRepository : MongoRepository<PatientDiagnosis>, IDiagnosisArchiveRepository
{
    private readonly ApiSettings _apiSettings;

    /// <summary>
    /// Initializes a new instance of the <see cref="DiagnosisArchiveRepository"/> class with the specified API settings and MongoDB database. 
    /// The API settings are used to determine the collection name for storing archived patient diagnoses.
    /// </summary>
    /// <param name="apiSettings"></param>
    /// <param name="database"></param>
    /// <exception cref="ArgumentNullException"></exception>
    public DiagnosisArchiveRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database) : base(database)
    {
        if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
        _apiSettings = apiSettings.Value;
    } //For testing

    /// <summary>
    /// Inserts a single patient diagnosis record into the archive collection asynchronously. 
    /// This method uses the MongoDB driver to perform the insertion operation and ensures that the record is added to the correct collection as defined in the API settings.
    /// </summary>
    /// <param name="patientDiagnosis">The patient diagnosis record to insert.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public override async Task InsertOneAsync(PatientDiagnosis patientDiagnosis)
    {
        await Collection.InsertOneAsync(patientDiagnosis);
    }

    /// <summary>
    /// Deletes all patient diagnosis records from the archive collection that have a timestamp earlier than the specified date.
    /// </summary>
    /// <param name="date">The date before which patient diagnosis records should be deleted.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public async Task DeleteBeforeDate(DateTime date)
    {
        var filter = Builders<PatientDiagnosis>.Filter.Lt(po => po.Time, date);
        await Collection.DeleteManyAsync(filter);
    }

    /// <summary>
    /// Inserts a batch of patient diagnosis records into the archive collection asynchronously. 
    /// This method uses the MongoDB driver's bulk write functionality to efficiently insert multiple records in a single operation, improving performance when dealing with large datasets.
    /// </summary>
    /// <param name="observations">The collection of patient diagnosis records to insert.</param>
    /// <returns>The number of records successfully inserted.</returns>
    public async Task<long> InsertBatch(IEnumerable<PatientDiagnosis> observations)
    {
        var writes = new List<WriteModel<PatientDiagnosis>>();
        writes.AddRange(observations.Select(d => new InsertOneModel<PatientDiagnosis>(d)));

        var bulkInsert = await Collection.BulkWriteAsync(writes);

        return bulkInsert.InsertedCount;
    }

    /// <summary>
    /// Gets the name of the MongoDB collection used for storing archived patient diagnoses. 
    /// The collection name is determined based on the API settings, allowing for flexibility in configuration. 
    /// If the API settings do not specify a collection name, a default name of "archive_patients_diagnosis" is used.
    /// </summary>
    /// <returns>The name of the MongoDB collection for archived patient diagnoses.</returns>
    public override string GetCollectionName()
    {
        return _apiSettings.ArchivePatientsDiagnosis ?? "archive_patients_diagnosis";
    }

    /// <summary>
    /// Creates indexes on the MongoDB collection for archived patient diagnoses to optimize query performance.
    /// </summary>
    /// <returns>A task representing the asynchronous operation.</returns>
    public override async Task CreateIndexes()
    {
        var options = new CreateIndexOptions<PatientDiagnosis> { Background = true, Unique = false };

        var indexes = new List<CreateIndexModel<PatientDiagnosis>>
        {
            new("{ patientid: 1 }", options)
        };

        await MongoUtils.EnsureIndexes(Collection, indexes);
    }
}