using System.Security.Claims;
using ZB.MOM.WW.MxGateway.Server.Dashboard;

namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;

public sealed class DashboardAutoLoginAuthenticationHandlerTests
{
    /// <summary>The default auto-login user mints an authenticated principal with both dashboard roles.</summary>
    [Fact]
    public void CreatePrincipal_MintsAuthenticatedMultiRoleUser()
    {
        ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("multi-role");

        Assert.True(principal.Identity!.IsAuthenticated);
        Assert.Equal("multi-role", principal.Identity!.Name);
        Assert.True(principal.IsInRole(DashboardRoles.Admin));
        Assert.True(principal.IsInRole(DashboardRoles.Viewer));
    }

    /// <summary>A null, empty, or whitespace-only user falls back to the configured default user.</summary>
    /// <param name="user">The blank/whitespace/null user under test.</param>
    [Theory]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("   ")]
    public void CreatePrincipal_BlankUser_FallsBackToDefault(string? user)
    {
        ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal(user);

        Assert.Equal(DashboardAutoLoginAuthenticationHandler.DefaultUser, principal.Identity!.Name);
    }

    /// <summary>Leading/trailing whitespace around the user name is trimmed before minting the principal.</summary>
    [Fact]
    public void CreatePrincipal_TrimsUser()
    {
        ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("  multi-role  ");

        Assert.Equal("multi-role", principal.Identity!.Name);
    }

    /// <summary>A custom user name preserves its identity name and still receives both dashboard roles.</summary>
    [Fact]
    public void CreatePrincipal_CustomUser_PreservesNameAndRoles()
    {
        ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("gw-viewer");

        Assert.Equal("gw-viewer", principal.Identity!.Name);
        Assert.True(principal.IsInRole(DashboardRoles.Admin));
        Assert.True(principal.IsInRole(DashboardRoles.Viewer));
    }
}
