using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Infrastructure.Repositories;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using Options = Microsoft.Extensions.Options.Options;

namespace adas_core.Test.Repositories;

[TestFixture]
[Category("Integration")]
public class ObservationArchiveRepositoryTest
{
    [OneTimeSetUp]
    public async Task Init()
    {
        _optionsApiSettings = Options.Create(_apiSettings);

        var patientObservation1 = new PatientObservation
        {
            PatientId = PatientId,
            Code = "263490005",
            CodingSystem = "SNM",
            Name = "Estado",
            Status = StatusEnum.Type.Ok,
            Time = Now,
            Value = "Sin alergias conocidas"
        };

        var patientObservation2 = new PatientObservation
        {
            PatientId = PatientId,
            Code = "300916003",
            CodingSystem = "SNM",
            Name = "¿Alergia al látex?",
            Status = StatusEnum.Type.Ok,
            Time = Now.AddDays(-1),
            Value = "No"
        };

        await IntegrationDb.Database.DropCollectionAsync("archive_patients_observations");
        await IntegrationDb.Database.CreateCollectionAsync("archive_patients_observations");

        _repository = new ObservationArchiveRepository(_optionsApiSettings, IntegrationDb.Database);

        await _repository.InsertOneAsync(patientObservation1);
        await _repository.InsertOneAsync(patientObservation2);
    }

    private ObservationArchiveRepository _repository;

    private readonly ApiSettings _apiSettings = new()
    {
        ArchivePatientsDiagnosis = "archive_patients_observations"
    };

    private IOptions<ApiSettings> _optionsApiSettings;

    private static readonly DateTime Now = DateTime.Now;
    private static readonly ObjectId PatientId = ObjectId.GenerateNewId();


    /// <summary>
    /// Verifies that the repository's <c>DeleteBeforeDate</c> method removes all patient observations
    /// dated before the specified cutoff, leaving only a single observation remaining in the collection.
    /// </summary>
    [Test]
        public async Task DeleteBeforeDate()
        {
            var filter = Builders<PatientObservation>.Filter.Eq(p => p.PatientId, PatientId);
    
            var result = await _repository.Collection.FindAsync(filter);
    
            Assert.That(result, Is.Not.Null);
            Assert.That(result.ToList(), Has.Count.GreaterThan(1));
    
            await _repository.DeleteBeforeDate(Now);
    
            var resultDelete = await _repository.Collection.FindAsync(filter);
    
            Assert.That(resultDelete, Is.Not.Null);
            Assert.That(resultDelete.ToList(), Has.Count.EqualTo(1));
        }
}