using e_suite.API.Common.exceptions;
using e_suite.API.Common.models;
using eSuite.Core.Miscellaneous;
using eSuite.Core.Sequences;
using NUnit.Framework;
using SequenceManager.UnitTests.Helpers;

namespace SequenceManager.UnitTests;

[TestFixture]
internal class DeleteSequenceUnitTests : SequenceManagerTestBase
{
    [SetUp]
    public override async Task Setup()
    {
        await base.Setup();
    }

    [Test]
    public void DeleteSequence_SequenceNotFound_ThrowsException()
    {
        // Arrange
        var sequence = new Sequence
        {
            GeneralIdRef = new GeneralIdRef { Guid = new Guid("{E32DAA1C-CECD-41F4-BD5E-F5AF83EF94C1}") },
            Increment = 1,
            Name = "Sequence name",
            Pattern = "{DD}",
            RolloverType = Rollover.Day,
            Seed = 1
        };

        // Act
        // Assert
        Assert.ThrowsAsync<NotFoundException>(async () => { await SequenceManager.DeleteSequence(AuditUserDetails, sequence.GeneralIdRef, default); });
    }

    [Test]
    public async Task DeleteSequence_AlreadyDeleted_ThrowsException()
    {
        // Arrange
        var sequenceGuid = new Guid("{EE90AF25-881E-4590-8A14-F351048A980A}");

        SequenceManagerRepository.Sequences.Add(new e_suite.Database.Core.Tables.Sequences.Sequence
        {
            Id = 999,
            Guid = sequenceGuid,
            Increment = 1,
            Name = "Test sequence",
            Pattern = "{DD}",
            Rollover = Rollover.Day,
            Seed = 1
        });
        
        await SequenceManager.DeleteSequence(AuditUserDetails, new GeneralIdRef { Guid = sequenceGuid }, default);

        // Act & Assert
        Assert.ThrowsAsync<NotFoundException>(async () =>
        {
            await SequenceManager.DeleteSequence(AuditUserDetails, new GeneralIdRef { Guid = sequenceGuid },
                default);
        });
    }

    [Test]
    public async Task DeleteSequence_EverythingOk_DeletesSequence()
    {
        // Arrange
        var sequenceGuid = new Guid("{EE90AF25-881E-4590-8A14-F351048A980A}");

        SequenceManagerRepository.Sequences.Add(new e_suite.Database.Core.Tables.Sequences.Sequence
        {
            Id = 999,
            Guid = sequenceGuid,
            Increment = 1,
            Name = "Test sequence",
            Pattern = "{DD}",
            Rollover = Rollover.Day,
            Seed = 1
        });

        // Act
        await SequenceManager.DeleteSequence(AuditUserDetails, new GeneralIdRef { Guid = sequenceGuid }, default);

        // Assert
        var result = await SequenceManagerRepository.GetSequenceById(new GeneralIdRef { Guid = sequenceGuid }, default);

        Assert.Multiple(() =>
        {
            Assert.That(result, Is.Not.Null);
            Assert.That(result?.Name, Is.EqualTo("Test sequence"));
            Assert.That(result?.Deleted, Is.True);
        });
    }
}