using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Security;
using ZB.MOM.WW.OtOpcUa.Security.Auth;

namespace ZB.MOM.WW.OtOpcUa.Security.Tests;

public class AddOtOpcUaAuthWiringTests
{
    private static async Task<Type> CookieHandlerTypeAsync(bool disableLogin)
    {
        var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["Security:Auth:DisableLogin"] = disableLogin ? "true" : "false",
        }).Build();

        var services = new ServiceCollection();
        services.AddLogging();
        services.AddOtOpcUaAuth(config);

        await using var sp = services.BuildServiceProvider();
        var provider = sp.GetRequiredService<IAuthenticationSchemeProvider>();
        var scheme = await provider.GetSchemeAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return scheme!.HandlerType;
    }

    [Fact]
    public async Task DisableLogin_true_registers_autologin_handler_for_cookie_scheme()
        => (await CookieHandlerTypeAsync(true)).ShouldBe(typeof(AutoLoginAuthenticationHandler));

    [Fact]
    public async Task DisableLogin_false_registers_cookie_handler()
        => (await CookieHandlerTypeAsync(false)).ShouldBe(typeof(CookieAuthenticationHandler));
}
