using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Infrastructure.Repositories;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using Serilog;
using static adas_core.Domain.Models.MongoModels.Section;
using Options = Microsoft.Extensions.Options.Options;

namespace adas_core.Test.Repositories;

/// <summary>
/// Serves as an integration test fixture for the SectionRepository type.
/// </summary>
/// <remarks>
/// Categorized as <c>"Integration"</c> via <see cref="CategoryAttribute"/> to group related test execution.
/// </remarks>
/// <!-- aidoc:v1 sig=b68ae8f -->
[TestFixture]
[Category("Integration")]
public class SectionRepositoryTest
{
    /// <summary>
    /// Initializes the integration test fixture by seeding two <see cref="Section"/> entities
    /// (<c>UCIP1</c> and <c>UCIP2</c>) with their associated <see cref="Box"/> data into the
    /// <c>config_sections</c> MongoDB collection through <see cref="SectionRepository"/>.
    /// </summary>
    /// <!-- aidoc:v1 sig=81c0015 body=44a9993 -->
    [OneTimeSetUp]
    public async Task Init()
    {
        _optionsApiSettings = Options.Create(_apiSettings);

        var boxes = new List<Box>
        {
            new() { Bed = "bed1", IsActive = true },
            new() { Bed = "bed2", IsActive = true },
            new() { Bed = "bed3", IsActive = true },
            new() { Bed = "bed4", IsActive = true },
            new() { Bed = "bed5", IsActive = true },
            new() { Bed = "bed6", IsActive = true }
        };

        var section1 = new Section
        {
            _id = SectionId1,
            Id = "UCIP1",
            SectionTitle = "UCI PEDIÁTRICA 1",
            PointOfCare = "UCIP1",
            Items =
            [
                new SectionItem
                {
                    Group = "Pasillo 1",
                    Boxes = boxes
                }
            ]
        };

        var section2 = new Section
        {
            _id = SectionId2,
            Id = "UCIP2",
            SectionTitle = "UCI PEDIÁTRICA 2",
            PointOfCare = "UCIP2",
            Items =
            [
                new SectionItem
                {
                    Group = "Pasillo 1",
                    Boxes = boxes
                }
            ]
        };

        //await IntegrationDb.Database.DropCollectionAsync("config_sections");
        await IntegrationDb.Database.CreateCollectionAsync("config_sections");

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

        await _repository.InsertOneAsync(section1);
        await _repository.InsertOneAsync(section2);
    }

    private SectionRepository _repository;

    private readonly ApiSettings _apiSettings = new()
    {
        ConfigSections = "config_sections"
    };

    private IOptions<ApiSettings> _optionsApiSettings;

    private static readonly ObjectId SectionId1 = ObjectId.GenerateNewId();
    private static readonly ObjectId SectionId2 = ObjectId.GenerateNewId();

    /// <summary>
    /// Verifies that <see cref="_repository"/>.<see cref="GetAll"/> returns a non-null collection containing the expected number of <c>Sections</c>.
    /// </summary>
    /// <!-- aidoc:v1 sig=42e95a2 body=7729b1c -->
    [Test]
    public async Task GetAll_Return_List_Sections()
    {
        var result = await _repository.GetAll();

        Assert.That(result, Is.Not.Null);
        Assert.That(result, Has.Count.EqualTo(2));
    }

    /// <summary>
    /// Verifies that the repository's <c>FindBySection</c> method returns <see langword="null"/> when invoked with an empty section name, covering the not-found case for empty input.
    /// </summary>
    /// <!-- aidoc:v1 sig=2417a8d body=26e0f11 -->
    [Test]
    public async Task FindBySection_Not_Find_Return_null()
    {
        var result = await _repository.FindBySection("");

        Assert.That(result, Is.Null);
    }

    /// <summary>
    /// Verifies that FindBySection returns a matching section record when queried by the title "UCI PEDIÁTRICA 2", ensuring the result is not <see langword="null"/> and the returned SectionTitle equals the queried value.
    /// </summary>
    /// <!-- aidoc:v1 sig=9ae4667 body=a76a58e -->
    [Test]
    public async Task FindBySection_Find_Return_Section()
    {
        var result = await _repository.FindBySection("UCI PEDIÁTRICA 2");

        Assert.That(result, Is.Not.Null);
        Assert.That(result!.SectionTitle, Is.EqualTo("UCI PEDIÁTRICA 2"));
    }

    /// <summary>
    /// Verifies that the repository's FindByPointOfCare method returns <c>null</c> when invoked with an empty point of care value that does not match any existing record.
    /// </summary>
    /// <!-- aidoc:v1 sig=ba51c3a body=b62b9bf -->
    [Test]
    public async Task FindByPointOfCare_Not_Find_Return_null()
    {
        var result = await _repository.FindByPointOfCare("");

        Assert.That(result, Is.Null);
    }

    /// <summary>
    /// Verifies that the repository's FindByPointOfCare method successfully retrieves a non-null section for the point of care identifier "UCIP1" and confirms that the returned section's SectionTitle equals "UCI PEDIÁTRICA 1".
    /// </summary>
    /// <!-- aidoc:v1 sig=0e320dc body=292d2c3 -->
    [Test]
    public async Task FindByPointOfCare_Find_Return_Section()
    {
        var result = await _repository.FindByPointOfCare("UCIP1");

        Assert.That(result, Is.Not.Null);
        Assert.That(result!.SectionTitle, Is.EqualTo("UCI PEDIÁTRICA 1"));
    }

    /// <summary>
    /// Verifies that <see cref="FindById"/> returns <see langword="null"/> when the requested entity cannot be located, using an empty identifier to simulate the not-found scenario.
    /// </summary>
    /// <!-- aidoc:v1 sig=fd1f8c3 body=7ddac2c -->
    [Test]
    public async Task FindById_Not_Find_Return_null()
    {
        var result = await _repository.FindById("");

        Assert.That(result, Is.Null);
    }

    /// <summary>
    /// Verifies that the repository's FindById method successfully retrieves a Section by its identifier, ensuring the returned object is not null and its SectionTitle matches the expected value.
    /// Tests the lookup of the section with identifier "UCIP1" and asserts the returned title is "UCI PEDIÁTRICA 1".
    /// </summary>
    /// <!-- aidoc:v1 sig=4c116ce body=b30a392 -->
    [Test]
    public async Task FindById_Find_Return_Section()
    {
        var result = await _repository.FindById("UCIP1");

        Assert.That(result, Is.Not.Null);
        Assert.That(result!.SectionTitle, Is.EqualTo("UCI PEDIÁTRICA 1"));
    }

    /// <summary>
    /// Verifies that invoking the repository's <c>FindById</c> with a freshly generated <see cref="MongoDB.Bson.ObjectId"/> that does not correspond to any stored entity returns <see langword="null"/>.
    /// </summary>
    /// <!-- aidoc:v1 sig=dcf9ad4 body=c6d06bf -->
    [Test]
    public async Task FindById_Not_Find_Id_Return_null()
    {
        var result = await _repository.FindById(ObjectId.GenerateNewId());

        Assert.That(result, Is.Null);
    }

    /// <summary>
    /// Verifies that the repository's FindById method successfully retrieves the section identified by SectionId2, confirming the returned section is not null and its SectionTitle equals "UCI PEDIÁTRICA 2".
    /// </summary>
    /// <!-- aidoc:v1 sig=15aea3b body=8a5a33f -->
    [Test]
    public async Task FindById_Find_Id_Return_Section()
    {
        var result = await _repository.FindById(SectionId2);

        Assert.That(result, Is.Not.Null);
        Assert.That(result!.SectionTitle, Is.EqualTo("UCI PEDIÁTRICA 2"));
    }

    /// <summary>
    /// Verifies that the FindByLocation method returns a non-null empty list when no patient records match the specified PatientLocation.
    /// </summary>
    /// <!-- aidoc:v1 sig=e5d1cc6 body=8f2c7f5 -->
    [Test]
    public async Task FindByLocation_Not_Find_Return_Emty_List()
    {
        PatientLocation location = new("UCIP3", "bed1");
        var result = await _repository.FindByLocation(location);

        Assert.That(result, Is.Not.Null);
        Assert.That(result, Is.Empty);
    }

    /// <summary>
    /// Tests that the repository's FindByLocation method returns a list with exactly one result for the specified <see cref="PatientLocation"/>, and that the returned record contains the expected section title.
    /// </summary>
    /// <!-- aidoc:v1 sig=4154fd5 body=4e74a65 -->
    [Test]
    public async Task FindByLocation_Find_Return_List()
    {
        PatientLocation location = new("UCIP1", "bed1");
        var result = await _repository.FindByLocation(location);

        Assert.That(result, Is.Not.Null);
        Assert.That(result, Has.Count.EqualTo(1));
        Assert.That(result[0].SectionTitle, Is.EqualTo("UCI PEDIÁTRICA 1"));
    }


    /// <summary>
    /// Tests the insert, update, and delete lifecycle of a <see cref="Section"/> entity through the repository, verifying that a section can be inserted, retrieved by its identifier, updated with new content, and subsequently deleted.
    /// </summary>
    /// <!-- aidoc:v1 sig=1b52a18 body=59f8803 -->
    [Test]
    public async Task InsertUpdateAndDeleteSection()
    {
        var updateId = ObjectId.GenerateNewId();

        var boxes = new List<Box>
        {
            new() { Bed = "bed1", IsActive = true },
            new() { Bed = "bed2", IsActive = true },
            new() { Bed = "bed3", IsActive = true },
            new() { Bed = "bed4", IsActive = true },
            new() { Bed = "bed5", IsActive = true },
            new() { Bed = "bed6", IsActive = true }
        };

        var section1 = new Section
        {
            _id = ObjectId.GenerateNewId(),
            Id = "UCIP_U_Id",
            SectionTitle = "UCI PEDIÁTRICA U",
            PointOfCare = "UCIP_U",
            Items =
            [
                new SectionItem
                {
                    Group = "Pasillo 1",
                    Boxes = boxes
                }
            ]
        };

        var sectionUpdate = new Section
        {
            _id = updateId,
            Id = "UCIP_U_Id",
            SectionTitle = "UCI PEDIÁTRICA UPDATE",
            PointOfCare = "UCIP_U",
            Items =
            [
                new SectionItem
                {
                    Group = "Pasillo 1",
                    Boxes = boxes
                }
            ]
        };


        await _repository.InsertOneAsync(section1);
        try
        {
            await _repository.Collection.CountDocumentsAsync(_ => true);
        }
        catch (Exception ex)
        {
            Log.Debug(ex.ToString());
            throw;
        }

        var resultInsert = await _repository.FindById("UCIP_U_Id");

        Assert.That(resultInsert, Is.Not.Null);
        Assert.That(resultInsert.SectionTitle, Is.EqualTo("UCI PEDIÁTRICA U"));

        var result = await _repository.UpdateSection(sectionUpdate);

        Assert.That(result, Is.Not.Null);
        Assert.That(result.SectionTitle, Is.Not.EqualTo("UCI PEDIÁTRICA U"));
        Assert.That(result.SectionTitle, Is.EqualTo("UCI PEDIÁTRICA UPDATE"));

        await _repository.Collection.DeleteOneAsync(s => s.Id == "UCIP_U_Id");

        var resultDelete = await _repository.FindById("UCIP_U_Id");

        Assert.That(resultDelete, Is.Null);
    }
}