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

namespace eSuite.API.UnitTests.Controllers.FormsControllerUnitTests;

[TestFixture]
public class CreateFormsTemplateUnitTests : FormsControllerTestBase
{
    [SetUp]
    public override async Task Setup()
    => await base.Setup();


    [Test]
    public async Task CreateCustomField_WithPredifaindGuid_RetunrOK()
    {
        //Arrange
        var formGuid = new Guid("ff738e5b-1cf4-4530-8543-280b22b7f38f");
        var formDefinition = "TestDef";
        var formName = "TestName";
        var createFormTemplat = new CreateFormTemplate
        {
            Definition = formDefinition,
            Name = formName,
            Guid = formGuid,
        };

        //Act
        var res = await _formsController.CreateFormTemplate(createFormTemplat);

        //Assert
        _formsManagerMock!.Verify(x => x.CreateFormTemplateAsync(It.IsAny<AuditUserDetails>(), It.Is<CreateFormTemplate>(f => f.Name == formName && f.Definition == formDefinition && f.Guid == formGuid), It.IsAny<CancellationToken>()));
        Assert.That(res.GetType(), Is.EqualTo(typeof(OkResult)));
    }

    [Test]
    public async Task CreateCustomfield_WithOutAPredifiandGuid_rturnsOk()
    {
        //Arrange
        var formDefinition = "TestDef";
        var formName = "TestName";
        var createFormTemplat = new CreateFormTemplate
        {
            Definition = formDefinition,
            Name = formName,
        };

        //Act
        var res = await _formsController.CreateFormTemplate(createFormTemplat);

        //Assert
        _formsManagerMock!.Verify(x => x.CreateFormTemplateAsync(It.IsAny<AuditUserDetails>(), It.Is<CreateFormTemplate>(f => f.Name == formName && f.Definition == formDefinition && f.Guid == null), It.IsAny<CancellationToken>()));
        Assert.That(res.GetType(), Is.EqualTo(typeof(OkResult)));
    }

    [Test]
    public void CreateCustomField_WithExistingGuid_ReturnsBadRequest()
    {
        //Arrange
        var formGuid = new Guid("c218dd57-e641-4e82-9d2e-28e952360fdf");
        var formDefinition = "TestDef";
        var formName = "TestName";
        const string errorMesage = "Guid error";
        var createFormTemplat = new CreateFormTemplate
        {
            Definition = formDefinition,
            Name = formName,
            Guid = formGuid,
        };
        _formsManagerMock?.Setup(x => x.CreateFormTemplateAsync(It.IsAny<AuditUserDetails>(), It.Is<CreateFormTemplate>(x => x.Guid == formGuid), It.IsAny<CancellationToken>())).ThrowsAsync(new ExistsException(errorMesage));

        //Assert
        Assert.ThrowsAsync<ExistsException>(async () =>
        {
            //Act
            var res = await _formsController.CreateFormTemplate(createFormTemplat);
        });
    }
}
