using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Security;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Security;

namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;

/// <summary>
/// Security-023 (membership-validation half): the LDAP-group-mapping <c>Role</c> arrives
/// as a free string over the CLI/Management API. The single server-side write path
/// (<c>ManagementActor.HandleCreateRoleMapping</c> / <c>HandleUpdateRoleMapping</c>) now
/// rejects any role that is not in the canonical <see cref="Roles.All"/> set, returning a
/// <c>COMMAND_FAILED</c> error before any DB write. A non-canonical role never functioned
/// (no authorization policy or ManagementActor check matched it), so rejecting it removes
/// a silent-misconfiguration footgun rather than changing behaviour.
/// </summary>
/// <remarks>
/// Per Security-023's scope: only the membership check is added. The pre-existing
/// case-sensitivity asymmetry (case-sensitive UI <c>RequireClaim</c> vs case-insensitive
/// ManagementActor authz) is a separately-deferred change and is NOT touched — the
/// membership check accepts a correctly-cased canonical role and stores it verbatim.
/// </remarks>
public class RoleMappingValidationTests : TestKit, IDisposable
{
    private readonly ISecurityRepository _securityRepo;
    private readonly IAuditService _auditService;
    private readonly ServiceCollection _services;

    public RoleMappingValidationTests()
    {
        _securityRepo = Substitute.For<ISecurityRepository>();
        _auditService = Substitute.For<IAuditService>();

        _services = new ServiceCollection();
        _services.AddScoped(_ => _securityRepo);
        _services.AddScoped(_ => _auditService);
    }

    private IActorRef CreateActor()
    {
        var sp = _services.BuildServiceProvider();
        return Sys.ActorOf(Props.Create(() => new ManagementActor(
            sp, NullLogger<ManagementActor>.Instance)));
    }

    // CreateRoleMappingCommand / UpdateRoleMappingCommand both require Administrator
    // (see ManagementActor.GetRequiredRole), so the test principal carries that role.
    private static ManagementEnvelope Envelope(object command) =>
        new(new AuthenticatedUser("admin", "admin", new[] { Roles.Administrator }, Array.Empty<string>()),
            command, Guid.NewGuid().ToString("N"));

    void IDisposable.Dispose() => Shutdown();

    [Fact]
    public void CreateRoleMapping_UnknownRole_ReturnsError_NoRowInserted()
    {
        var actor = CreateActor();
        actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Admins", "Wizard")));

        var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
        Assert.Equal("COMMAND_FAILED", response.ErrorCode);
        Assert.Contains("Wizard", response.Error);
        _securityRepo.DidNotReceiveWithAnyArgs().AddMappingAsync(default!, default);
    }

    [Fact]
    public void CreateRoleMapping_MisspelledCanonicalRole_ReturnsError_NoRowInserted()
    {
        // A pure typo of a real role ("Deploer" for "Deployer") is exactly the silent
        // footgun Security-023 describes: it would stamp a role claim no policy matches.
        var actor = CreateActor();
        actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", "Deploer")));

        var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
        Assert.Equal("COMMAND_FAILED", response.ErrorCode);
        _securityRepo.DidNotReceiveWithAnyArgs().AddMappingAsync(default!, default);
    }

    [Fact]
    public void UpdateRoleMapping_UnknownRole_ReturnsError_NoRowUpdated()
    {
        var actor = CreateActor();
        actor.Tell(Envelope(new UpdateRoleMappingCommand(7, "SCADA-Admins", "Wizard")));

        var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
        Assert.Equal("COMMAND_FAILED", response.ErrorCode);
        Assert.Contains("Wizard", response.Error);
        // Rejected before the mapping is even looked up.
        _securityRepo.DidNotReceiveWithAnyArgs().GetMappingByIdAsync(default, default);
        _securityRepo.DidNotReceiveWithAnyArgs().UpdateMappingAsync(default!, default);
    }

    [Fact]
    public void CreateRoleMapping_CanonicalRole_Succeeds_RowInserted()
    {
        LdapGroupMapping? inserted = null;
        _securityRepo
            .When(r => r.AddMappingAsync(Arg.Any<LdapGroupMapping>(), Arg.Any<CancellationToken>()))
            .Do(ci => inserted = ci.Arg<LdapGroupMapping>());

        var actor = CreateActor();
        actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", Roles.Deployer)));

        ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
        Assert.NotNull(inserted);
        // A correctly-cased canonical role round-trips unchanged.
        Assert.Equal(Roles.Deployer, inserted!.Role);
        Assert.Equal("SCADA-Deploy", inserted.LdapGroupName);
    }

    [Fact]
    public void CreateRoleMapping_LowercaseRole_StoresCanonicalCasing()
    {
        // arch-review C5: ASP.NET RequireClaim policies compare Role ordinal
        // case-sensitively while the actor compares OrdinalIgnoreCase. A row stored
        // as "deployer" would pass every actor gate but fail every UI policy (a
        // CLI-works/UI-403s split-brain). The write path now canonicalizes to the
        // Roles.All casing, so the stored value is always "Deployer".
        LdapGroupMapping? inserted = null;
        _securityRepo
            .When(r => r.AddMappingAsync(Arg.Any<LdapGroupMapping>(), Arg.Any<CancellationToken>()))
            .Do(ci => inserted = ci.Arg<LdapGroupMapping>());

        var actor = CreateActor();
        actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", "deployer")));

        ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
        Assert.NotNull(inserted);
        Assert.Equal("Deployer", inserted!.Role); // canonical, not the verbatim "deployer"
    }

    [Fact]
    public void UpdateRoleMapping_LowercaseRole_StoresCanonicalCasing()
    {
        var existing = new LdapGroupMapping("SCADA-Deploy", Roles.Viewer) { Id = 7 };
        _securityRepo.GetMappingByIdAsync(7, Arg.Any<CancellationToken>()).Returns(existing);
        LdapGroupMapping? updated = null;
        _securityRepo
            .When(r => r.UpdateMappingAsync(Arg.Any<LdapGroupMapping>(), Arg.Any<CancellationToken>()))
            .Do(ci => updated = ci.Arg<LdapGroupMapping>());

        var actor = CreateActor();
        actor.Tell(Envelope(new UpdateRoleMappingCommand(7, "SCADA-Deploy", "deployer")));

        ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
        Assert.NotNull(updated);
        Assert.Equal("Deployer", updated!.Role);
    }
}
