using e_suite.API.Common.repository;
using e_suite.Database.Audit;
using e_suite.Database.Core.Extensions;
using e_suite.Database.Core.Tables.UserManager;
using e_suite.UnitTestCore;
using eSuite.Core.Miscellaneous;
using MockQueryable;

namespace SSOManager.UnitTests.Helpers;

public class FakeSsoManagerRepository : FakeRepository, ISsoManagerRepository
{
    public List<SsoProvider> SsoProviders = [];

    public FakeSsoManagerRepository()
    {
        SsoProviders.Add(new SsoProvider
        {
            Id = 1,
            Name = "Test provider",
            ClientId = "SecretClientId",
            ClientSecret = "NotTellingYou",
            Deleted = false,
            IsPublic = true,
            AuthorizationEndpoint = "AuthorizationEndpoint",
            TokenEndpoint = "TokenEndpoint",
            ValidIssuer = "ValidIssuer",
            Guid = new Guid("{14703B56-8F70-4D9D-9061-E62EC0D446BC}")
        });
    }

    public IQueryable<SsoProvider> GetSsoProviders()
    {
        return SsoProviders.BuildMock();
    }

    public async Task<SsoProvider?> GetSsoProviderAsync(IGeneralIdRef generalIdRef, CancellationToken cancellationToken)
    {
        return await GetSsoProviders().FindByGeneralIdRefAsync(generalIdRef, cancellationToken);
    }

    public Task CreateNewSsoProviderAsync(
        AuditUserDetails auditUserDetails,
        SsoProvider newSsoProvider,
        CancellationToken cancellationToken
    )
    {
        if (SsoProviders.Any(x => x.Name.Equals(newSsoProvider.Name, StringComparison.InvariantCultureIgnoreCase)))
            throw new Exception("SsoProvider Already exists");

        SsoProviders.Add(newSsoProvider);
        return Task.CompletedTask;
    }

    public Task EditNewSsoProviderAsync(
        AuditUserDetails auditUserDetails,
        SsoProvider ssoProvider,
        CancellationToken cancellationToken
    )
    {
        var realSsoProvider = SsoProviders.Single(x => x.Id == ssoProvider.Id);

        realSsoProvider.Guid = ssoProvider.Guid;
        realSsoProvider.Deleted = ssoProvider.Deleted;
        realSsoProvider.AuthorizationEndpoint = ssoProvider.AuthorizationEndpoint;
        realSsoProvider.ClientId = ssoProvider.ClientId;
        realSsoProvider.ClientSecret = ssoProvider.ClientSecret;
        realSsoProvider.IsPublic = ssoProvider.IsPublic;
        realSsoProvider.Name = ssoProvider.Name;
        realSsoProvider.TokenEndpoint = ssoProvider.TokenEndpoint;
        realSsoProvider.ValidIssuer = ssoProvider.ValidIssuer;

        return Task.CompletedTask;
    }
}