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

public class ConfigSecretScrubberTests
{
    [Fact]
    public void Scrub_RedactsPasswordFields_AtAnyDepth()
    {
        var json = """{"Endpoint":"opc.tcp://x","UserIdentity":{"Username":"u","Password":"p"},"CertificatePassword":"cp"}""";
        var (scrubbed, had) = ConfigSecretScrubber.Scrub(json);
        Assert.True(had);
        Assert.DoesNotContain("\"p\"", scrubbed);
        Assert.DoesNotContain("\"cp\"", scrubbed);
        Assert.Contains(ConfigSecretScrubber.Sentinel, scrubbed);
        Assert.Contains("opc.tcp://x", scrubbed); // non-secrets untouched
    }

    [Fact]
    public void Scrub_NoSecrets_ReturnsFalseFlag()
    {
        var (_, had) = ConfigSecretScrubber.Scrub("""{"Endpoint":"opc.tcp://x"}""");
        Assert.False(had);
    }

    [Theory]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("not-json{")]
    public void Scrub_NullEmptyOrMalformed_PassesThrough(string? input)
    {
        var (scrubbed, had) = ConfigSecretScrubber.Scrub(input);
        Assert.Equal(input, scrubbed);
        Assert.False(had);
    }

    [Fact]
    public void MergeSentinels_RestoresStoredSecrets_KeepsEdits()
    {
        var stored = """{"Endpoint":"old","UserIdentity":{"Password":"real"}}""";
        var incoming = $$$"""{"Endpoint":"new","UserIdentity":{"Password":"{{{ConfigSecretScrubber.Sentinel}}}"}}""";
        var merged = ConfigSecretScrubber.MergeSentinels(incoming, stored)!;
        Assert.Contains("\"new\"", merged);
        Assert.Contains("\"real\"", merged);
        Assert.DoesNotContain(ConfigSecretScrubber.Sentinel, merged);
    }

    // ── arch-review R2 N9: frozen scrubber fragment coverage ───────────────────

    // Frozen non-secret allowlist (arch-review R2 N9), mirroring RequiredRoleMatrixTests:
    // every string-typed property on the DataConnections config types must EITHER match
    // the scrubber's secret fragments (it gets elided) OR be listed here after a
    // deliberate "this is not a secret" decision. A new string property with neither
    // fails EveryConfigStringProperty_IsScrubbedOrDeliberatelyNonSecret, so a future
    // "SigningKey"/"Pin" cannot silently leak through List/Get/audit.
    private static readonly Dictionary<Type, string[]> KnownNonSecretStringProperties = new()
    {
        [typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections.OpcUaEndpointConfig)] = ["EndpointUrl", "SubscriptionDisplayName"],
        [typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections.OpcUaUserIdentityConfig)] = ["Username", "CertificatePath"],
        [typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections.MxGatewayEndpointConfig)] = ["Endpoint", "ClientName", "CaFile", "ServerName"],
        [typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections.OpcUaHeartbeatConfig)] = ["TagPath"],
        [typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections.OpcUaDeadbandConfig)] = [],
    };

    [Fact]
    public void EveryConfigStringProperty_IsScrubbedOrDeliberatelyNonSecret()
    {
        foreach (var (type, allowlist) in KnownNonSecretStringProperties)
        {
            var stringProps = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                .Where(p => p.PropertyType == typeof(string))
                .Select(p => p.Name);
            foreach (var name in stringProps)
            {
                var scrubbed = ConfigSecretScrubber.IsSecretName(name);
                var allowlisted = allowlist.Contains(name);
                Assert.True(scrubbed ^ allowlisted,
                    $"{type.Name}.{name}: must be EITHER fragment-scrubbed OR explicitly " +
                    "allowlisted as non-secret (and never both) — see arch-review R2 N9.");
            }
        }
    }

    [Theory]
    [InlineData("Password")]
    [InlineData("CertificatePassword")]
    [InlineData("ApiKey")]
    public void KnownSecretProperties_MatchTheFragmentList(string name)
        => Assert.True(ConfigSecretScrubber.IsSecretName(name));
}
