using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Infrastructure.Repositories;
using adas_core.Test.Utilities;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using Moq;
using Options = Microsoft.Extensions.Options.Options;

namespace adas_core.Test.Repositories;

[TestFixture]
[Category("Integration")]
public class PointOfCareRepositoryTests
{
    /// <summary>
    /// Performs one-time setup for integration tests by initializing mock dependencies and resetting the
    /// "pointOfCares" MongoDB collection before instantiating the <see cref="PointOfCareRepository"/>.
    /// </summary>
    [OneTimeSetUp]
        public async Task Init()
        {
            _optionsApiSettings = Options.Create(new ApiSettings());
            _mockCollection = new Mock<IMongoCollection<PointOfCare>>();
            _mockDatabase = new Mock<IMongoDatabase>();
            _mockDatabase.Setup(db => db.GetCollection<PointOfCare>(It.IsAny<string>(), null))
                .Returns(_mockCollection.Object);
    
            await IntegrationDb.Database.DropCollectionAsync("pointOfCares");
            await IntegrationDb.Database.CreateCollectionAsync("pointOfCares");
            _repository = new PointOfCareRepository(_optionsApiSettings, IntegrationDb.Database);
        }

    private PointOfCareRepository _repository;
    private Mock<IMongoCollection<PointOfCare>> _mockCollection;
    private Mock<IMongoDatabase> _mockDatabase;
    private IOptions<ApiSettings> _optionsApiSettings;

    /// <summary>
    /// Verifies that InsertOneAsync successfully inserts a valid point of care into the repository and that the record can be retrieved by its identifier.
    /// </summary>
    [Test]
        public async Task InsertOneAsync_ValidPointOfCare_InsertsSuccessfully()
        {
            // Arrange
            var pointOfCare = TestUtilities.CreateValidPointOfCare();
    
            // Act
            await _repository.InsertOneAsync(pointOfCare);
    
            // Assert
            var insertedPointOfCare = await _repository.FindById(pointOfCare.Id);
            Assert.That(insertedPointOfCare, Is.Not.Null, "Inserted point of care should not be null");
        }

    /// <summary>
    /// Verifies that the Delete method successfully removes a point of care from the repository when given a valid identifier.
    /// Inserts a point of care, deletes it by its identifier, and asserts that the entity can no longer be retrieved.
    /// </summary>
    [Test]
        public async Task Delete_ValidId_DeletesSuccessfully()
        {
            var pointOfCare = TestUtilities.CreateValidPointOfCare();
            await _repository.InsertOneAsync(pointOfCare);
    
            await _repository.Delete(pointOfCare.Id);
    
            // Assert
            var deletedPointOfCare = await _repository.FindById(pointOfCare.Id);
            Assert.That(deletedPointOfCare, Is.Null, "Deleted point of care should be null");
        }

    /// <summary>
    /// Verifies that <see cref="PointOfCare"/> entities can be updated successfully when valid data is provided, ensuring that modified properties such as <c>Room</c> and <c>Bed</c> are persisted and retrievable after the update operation.
    /// </summary>
    [Test]
        public async Task Update_ValidPointOfCare_UpdatesSuccessfully()
        {
            // Arrange
            var originalPointOfCare = TestUtilities.CreateValidPointOfCare();
            await _repository.InsertOneAsync(originalPointOfCare); // Insert the original point of care
    
            // Modify some properties to update
            originalPointOfCare.Room = "Updated Room";
            originalPointOfCare.Bed = "Updated Bed";
    
            // Act
            await _repository.Update(originalPointOfCare); // Update the point of care
    
            // Retrieve the updated point of care
            var updatedPointOfCare = await _repository.FindById(originalPointOfCare.Id);
    
            // Assert
            Assert.That(updatedPointOfCare, Is.Not.Null, "Updated point of care should not be null");
            Assert.That(updatedPointOfCare?.Room, Is.EqualTo(originalPointOfCare.Room), "Room should be updated");
            Assert.That(updatedPointOfCare?.Bed, Is.EqualTo(originalPointOfCare.Bed), "Bed should be updated");
        }


    /// <summary>
    /// Verifies that the repository's <c>FindById</c> method returns the correct <c>PointOfCare</c> document when queried with an existing identifier, by inserting a document and asserting that the retrieved entity matches the expected one.
    /// </summary>
    [Test]
        public async Task FindById_ExistingId_ReturnsPointOfCare()
        {
            // Arrange
            var pointOfCareId = ObjectId.GenerateNewId();
            var expectedPointOfCare = TestUtilities.CreateValidPointOfCare();
            expectedPointOfCare.Id = pointOfCareId;
    
            // Insert a PointOfCare document into the database
            await _repository.InsertOneAsync(expectedPointOfCare);
    
            // Act
            var result = await _repository.FindById(pointOfCareId);
    
            // Assert
            Assert.That(result, Is.Not.Null, "Returned PointOfCare should not be null");
            Assert.That(result!.Id, Is.EqualTo(expectedPointOfCare.Id), "Returned PointOfCare should have the expected ID");
            // Add additional assertions to compare other properties if needed
        }

    /// <summary>
    /// Verifies that FindByUnitAndStatus returns the matching <c>PointOfCare</c> documents when queried with an existing unit identifier and status.
    /// </summary>
    [Test]
        public async Task FindByUnitAndStatus_ExistingUnitAndStatus_ReturnsMatchingPointOfCares()
        {
            // Arrange
            var expectedPointOfCare = TestUtilities.CreateValidPointOfCare();
    
            // Insert PointOfCare documents into the database with the specified unit ID and status
    
            await _repository.InsertOneAsync(expectedPointOfCare);
    
            // Act
            var result = await _repository.FindByUnitAndStatus(expectedPointOfCare.UnitId, expectedPointOfCare.Status);
    
            var resultList = result.ToList();
            // Assert
            Assert.That(resultList, Is.Not.Null, "Returned collection should not be null");
            Assert.That(resultList.First().Id, Is.EqualTo(expectedPointOfCare.Id),
                "Returned collection should contain expected PointOfCare object");
        }

    /// <summary>
    /// Tests that <c>FindByRoom</c> returns the matching <c>PointOfCare</c> when a valid room is provided.
    /// Inserts a valid <c>PointOfCare</c> into the repository and verifies the search by room returns a non-null collection
    /// containing the expected entity. Assertions are only executed when the inserted <c>PointOfCare</c> has a non-null <c>Unit</c>.
    /// </summary>
    [Test]
        public async Task FindByRoom_ValidRoom_ReturnsMatchingPointOfCares()
        {
            var expectedPointOfCare = TestUtilities.CreateValidPointOfCare();
            await _repository.InsertOneAsync(expectedPointOfCare);
    
            // Act
            if (expectedPointOfCare.Unit != null)
            {
                var result = await _repository.FindByRoom(expectedPointOfCare.Room);
    
                var resultList = result?.ToList();
    
                // Assert
                Assert.That(resultList, Is.Not.Null, "Returned collection should not be null");
    
                Assert.That(resultList?.Any(p => p.Id == expectedPointOfCare.Id), Is.True,
                    "Returned collection should contain expected PointOfCare object");
            }
        }

    /// <summary>
    /// Verifies that the repository returns the matching PointOfCare when queried with a valid bed identifier.
    /// </summary>
    [Test]
        public async Task FindByBed_ValidBed_ReturnsMatchingPointOfCares()
        {
            var expectedPointOfCare = TestUtilities.CreateValidPointOfCare();
            await _repository.InsertOneAsync(expectedPointOfCare);
    
            // Act
            var result = await _repository.FindByBed(expectedPointOfCare.Bed);
    
            // Convert the result to a list or an array
            var resultList = result?.ToList();
    
            // Assert
            Assert.That(resultList, Is.Not.Null, "Returned collection should not be null");
    
            // Check if the expected point of care is contained within the result
            Assert.That(resultList?.First().Bed, Is.EqualTo(expectedPointOfCare.Bed),
                "Returned collection should contain expected PointOfCare object");
        }

    /// <summary>
    /// Verifies that the <c>GetAll</c> repository method returns all stored <c>PointOfCare</c> entries, including a newly inserted one identified by its assigned Id.
    /// </summary>
    [Test]
        public async Task GetAll_ReturnsAllPointOfCares()
        {
            var poc = TestUtilities.CreateValidPointOfCare();
            await _repository.InsertOneAsync(poc);
    
            var result = await _repository.GetAll();
    
            var resultList = result?.ToList();
            // Assert
            Assert.That(resultList?.Any(p => p.Id == poc.Id), Is.True,
                "Returned collection should contain the expected PointOfCare object with the specified Id");
        }
}