using e_suite.API.Common.exceptions;
using e_suite.API.Common.models;
using e_suite.Database.Audit;
using e_suite.Database.Core.Tables.Domain;
using e_suite.Modules.RoleManager.UnitTests.Helpers;
using eSuite.Core.Miscellaneous;
using eSuite.Core.Security;
using NUnit.Framework;

namespace e_suite.Modules.RoleManager.UnitTests;

[TestFixture]
public class DeleteRoleSecurityAccessUnitTests : RoleManagerTestBase
{
    [SetUp]
    public override async Task Setup()
    {
        await base.Setup();
    }
    
    private void AddRoleAccessToFakeRepo(Role role, SecurityAccess securityAccess)
    {
        var roleAccess = new RoleAccess
        {
            Role = role,
            RoleId = role.Id,
            AccessKey = (int)securityAccess
        };
        RoleManagerRepository.RoleAccess.Add(roleAccess);
    }

    [Test]
    public void DeleteRoleSecurityAccess_WhenRoleNotFound_ThrowsException()
    {
        //Arrange
        var auditUserDetails = new AuditUserDetails
        {
            UserId = 09127334,
            UserDisplayName = "Testy McTester",
            Comment = string.Empty
        };

        var accessToRemove = new DeleteRoleSecurityAccess
        {
            RoleId = new GeneralIdRef()
        };

            //Assert
        var actualResult = Assert.ThrowsAsync<NotFoundException>(async () =>
        {
            //Act
            await RoleManager.DeleteRoleSecurityAccess(auditUserDetails, accessToRemove, CancellationToken.None);
        });
        Assert.That(actualResult!.Message, Is.EqualTo("Role Not Found"));
    }

    [Test]
    public async Task DeleteRoleSecurityAccess_WhenRoleFound_DeletesAccessForRole()
    {
        //Arrange
        var auditUserDetails = new AuditUserDetails
        {
            UserId = 09127334,
            UserDisplayName = "Testy McTester",
            Comment = string.Empty
        };

        var role = new Role
        {
            Guid = new Guid("bbfb9730-37a1-4cbc-a066-4f2510adfeb4"),
            Id = 234,
            Name = "Testing role"
        };
        RoleManagerRepository.Roles.Add(role);

        AddRoleAccessToFakeRepo(role, SecurityAccess.AddUser);
        AddRoleAccessToFakeRepo(role, SecurityAccess.EditUser);
        AddRoleAccessToFakeRepo(role, SecurityAccess.DeleteUser);

        var accessToRemove = new DeleteRoleSecurityAccess
        {
            RoleId = new GeneralIdRef
            {
                Guid = role.Guid
            },
            SecurityAccess = new List<SecurityAccess>
            {
                SecurityAccess.AddUser,
                SecurityAccess.DeleteUser
            }
        };

        //Act
        await RoleManager.DeleteRoleSecurityAccess(auditUserDetails, accessToRemove, CancellationToken.None);

        //Assert
        Assert.That(RoleManagerRepository.RoleAccess.Count, Is.EqualTo(1));
    }
}