using e_suite.API.Common.exceptions;
using e_suite.API.Common.models;
using e_suite.Database.Audit;
using eSuite.Core.Miscellaneous;
using Microsoft.AspNetCore.Mvc;
using Moq;
using NUnit.Framework;

namespace eSuite.API.UnitTests.Controllers.CustomFieldControllerUnitTest;

[TestFixture]
public class EditCustomFieldUnitTest : CustomFieldControllerTestBase
{
    [SetUp]
    public override async Task Setup()
    {
        await base.Setup();
    }

    [Test]
    public async Task EditCustomField_EverythingOk_ReturnsOk()
    {
        //Arrange
        var editModel = new EditCustomFields
        {
            Id = new GeneralIdRef
            {
                Guid = new Guid("b87c50a6-09d4-4790-a158-24a477e91400")
            },
            DefaultValue = "Name"
        };

        //Act
        var res = await _customFieldController.EditField(editModel);

        //Assert
        _customFieldManagerMock?.Verify(x => x.EditFieldAsync(It.IsAny<AuditUserDetails>(), editModel, It.IsAny<CancellationToken>()), Times.Once());
        Assert.That(res.GetType(), Is.EqualTo(typeof(OkResult)));

    }

    [Test]
    public void EditCustomField_IdNotFound_Rturn404()
    {
        //Arrange
        const string errorText = "There is no CustomField with this Id";
        var editModel = new EditCustomFields
        {
            Id = new GeneralIdRef
            {
                Guid = new Guid("e2d8e755-8344-4577-b7c2-33a04d440915")
            },
            DefaultValue = "Name"
        };
        _customFieldManagerMock?.Setup(x => x.EditFieldAsync(It.IsAny<AuditUserDetails>(), editModel, It.IsAny<CancellationToken>())).ThrowsAsync(new NotFoundException(errorText));

        //Assert
        Assert.ThrowsAsync<NotFoundException>(async () =>
        {
            //Act
            var res = await _customFieldController.EditField(editModel);
        });
    }

    [Test]
    public void EditCustomField_NameExistsOnDiffrentField_Returns400()
    {
        //Arrange
        const string errorText = "Name Exists";
        var guid = new Guid("ad94a15f-df9b-4352-aafd-8f7726204ed7");

        var editModel = new EditCustomFields
        {
            Id = new GeneralIdRef
            {
                Guid = guid
            },
            DefaultValue = "Name",
            Name = "Name"
        };
        _customFieldManagerMock?.Setup(x => x.EditFieldAsync(It.IsAny<AuditUserDetails>(), It.Is<EditCustomFields>(x => x.Id.Guid == guid && x.Name == "Name"), It.IsAny<CancellationToken>())).ThrowsAsync(new ExistsException(errorText));

        //Assert
        Assert.ThrowsAsync<ExistsException>(async () =>
        {
            //Act
            var res = await _customFieldController.EditField(editModel);
        });
    }
}
