using e_suite.API.Common.exceptions;
using e_suite.Database.Core.Tables.UserManager;
using Moq;
using NUnit.Framework;

namespace eSuite.API.UnitTests.SingleSignOn.SingleSignOn;

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

    [Test]
    public async Task StartSingleSignOn_WhenNonSsoEmailProvided_ReturnsEmptyString()
    {
        //Arrange
        var email = "nonsso@let.me.in";

        //Act
        var result = await _singleSignOn.StartSingleSignOn(email, CancellationToken.None);
        
        //Assert
        Assert.That(result, Is.Empty);
    }

    [Test]
    public async Task StartSingleSignOn_WhenSsoEmailProvided_ReturnsExpectedAuthUrl()
    {
        //Arrange
        var email = "ssoUser@myemail.provider";
        var redirectUri = "https://esuite.test";

        var ssoProvider = new SsoProvider
        {
            Id = 10,
            AuthorizationEndpoint = "https://myAuthProvider.com/auth",
            ClientId = "testClientId"
        };

        _userManagerMock.Setup(x => x.GetSsoProviderForEmail(email, It.IsAny<CancellationToken>())).ReturnsAsync(ssoProvider);

        //Act
        var result = await _singleSignOn.StartSingleSignOn(email, CancellationToken.None);

        //Assert
        Assert.That( result, Is.EqualTo($"{ssoProvider.AuthorizationEndpoint}?response_type=code&client_id={ssoProvider.ClientId}&redirect_uri={redirectUri}/account/auth/{ssoProvider.Id}&scope=openid"));
    }

    [Test]
    public Task StartSingleSignOn_WhenInvalidSsoIdProvided_ThrowsNotFoundException()
    {
        //Arrange
        var ssoProviderId = 12345;

        //Act & Assert
        Assert.ThrowsAsync<NotFoundException>(async () =>
        {
            var result = await _singleSignOn.StartSingleSignOn(ssoProviderId, CancellationToken.None);
        });
        return Task.CompletedTask;
    }

    [Test]
    public async Task StartSingleSignOn_WhenValidSsoIdProvided_ReturnsExpectedAuthUrl()
    {
        //Arrange
        var ssoProviderId = 54321;
        var redirectUri = "https://esuite.test";

        var ssoProvider = new SsoProvider
        {
            Id = 10,
            AuthorizationEndpoint = "https://myAuthProvider.com/auth",
            ClientId = "testClientId"
        };

        _userManagerMock.Setup(x => x.GetSsoProviderById(ssoProviderId, It.IsAny<CancellationToken>())).ReturnsAsync(ssoProvider);

        //Act
        var result = await _singleSignOn.StartSingleSignOn(ssoProviderId, CancellationToken.None);

        //Assert
        Assert.That(result, Is.EqualTo($"{ssoProvider.AuthorizationEndpoint}?response_type=code&client_id={ssoProvider.ClientId}&redirect_uri={redirectUri}/account/auth/{ssoProvider.Id}&scope=openid"));
    }
}