using e_suite.Database.Audit.AuditEngine;
using e_suite.Database.Audit.UnitTests.Helpers;
using e_suite.Database.Audit.UnitTests.Helpers.Tables;
using NUnit.Framework;

namespace e_suite.Database.Audit.UnitTests.AuditEngineCore;

[TestFixture]
public class HardDeleteUnitTests : AuditEngineCoreTestBase
{
    [TestCase("")]
    [TestCase("Test Comment")]
    public async Task AddRow_TableHasSelfReferenceAndReferenceNull_AuditForHardDeleteRecorded(string auditComment)
    {
        //Arrrange
        var auditUserDetails = new AuditUserDetails
        {
            UserId = 1,
            UserDisplayName = "Testy McTester",
            Comment = auditComment
        };

        var leafTreeValue = new DeletableTreeValue
        {
            Id = 30000,
            Name = "Leaf Level item",
        };

        testDBContext.DeletableTreeValues.Add(leafTreeValue);
        await testDBContext.NoAuditSaveChangesAsync();

        //Act
        var itemToEdit = testDBContext.DeletableTreeValues.Single(x => x.Id == leafTreeValue.Id);
        testDBContext.DeletableTreeValues.Remove(itemToEdit);
        await testDBContext.SaveChangesAsync(auditUserDetails);

        //Assert
        Assert.That(testDBContext.DeletableTreeValues.Count(), Is.EqualTo(0));

        Assert.That(testDBContext.AuditDetails.Count(), Is.EqualTo(1));

        var auditDetail = testDBContext.AuditDetails.First();
        Assert.That(auditDetail.UserDisplayName, Is.EqualTo(auditUserDetails.UserDisplayName));
        Assert.That(auditDetail.UserId, Is.EqualTo(auditUserDetails.UserId));
        Assert.That(auditDetail.Comment, Is.EqualTo(auditUserDetails.Comment));

        Assert.That(auditDetail.Id, Is.EqualTo(1));

        Assert.That(auditDetail.Type, Is.EqualTo(AuditType.Purge.ToString()));

        Assert.That(testDBContext.AuditEntries.Count(), Is.EqualTo(1));

        var auditEntries = testDBContext.AuditEntries.ToList();
        var childAuditEntry = auditEntries[0];
        Assert.That(childAuditEntry.Id, Is.EqualTo(1));
        Assert.That(childAuditEntry.EntityName, Is.EqualTo(typeof(DeletableTreeValue).FullName));
        Assert.That(childAuditEntry.DisplayName, Is.EqualTo(leafTreeValue.Name));
        Assert.That(childAuditEntry.AuditLogId, Is.EqualTo(auditDetail.Id));
        Assert.That(childAuditEntry.PrimaryKey, Is.EqualTo($"{{\"Id\":{leafTreeValue.Id}}}"));
        Assert.That(childAuditEntry.IsPrimary, Is.True);

        Assert.That(testDBContext.AuditDrillHierarchies.Count(), Is.EqualTo(0));
    }
}