using System.Text.Json;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.GalaxyRepository;
using ZB.MOM.WW.GalaxyRepository.Grpc;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
using ZB.MOM.WW.MxGateway.Server.Sessions;

// ConstraintEnforcer enforces against the gateway's constraint-bearing identity; the shared library
// also defines an ApiKeyIdentity, so disambiguate to the gateway type.
using ApiKeyIdentity = ZB.MOM.WW.MxGateway.Server.Security.Authentication.ApiKeyIdentity;

namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;

public sealed class ConstraintEnforcerTests
{
    /// <summary>Verifies that read outside allowed subtree returns failure.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WhenOutsideReadSubtree_ReturnsFailure()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            ReadSubtrees = ["Area1/*"],
        });

        ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
            identity,
            "Other_001.PV",
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("read_scope", failure.ConstraintName);
    }

    /// <summary>Verifies that write with high classification returns failure and audits.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckWriteHandleAsync_WhenClassificationTooHigh_ReturnsFailureAndAudits()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out FakeAuditWriter auditWriter);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            WriteSubtrees = ["Area1/*"],
            MaxWriteClassification = 1,
        });
        GatewaySession session = CreateSession();
        session.TrackCommandReply(
            new MxCommand
            {
                Kind = MxCommandKind.AddItem,
                AddItem = new AddItemCommand
                {
                    ServerHandle = 12,
                    ItemDefinition = "Pump_001.PV",
                },
            },
            new MxCommandReply
            {
                ProtocolStatus = ZB.MOM.WW.MxGateway.Server.Grpc.MxAccessGrpcMapper.Ok(),
                AddItem = new AddItemReply { ItemHandle = 42 },
            });

        ConstraintFailure? failure = await enforcer.CheckWriteHandleAsync(
            identity,
            session,
            serverHandle: 12,
            itemHandle: 42,
            CancellationToken.None);
        Assert.NotNull(failure);

        await enforcer.RecordDenialAsync(identity, "Write", "42", failure, correlationId: null, CancellationToken.None);

        AuditEvent auditEvent = Assert.Single(auditWriter.Events);
        Assert.Equal("operator01", auditEvent.Actor);
        Assert.Equal("constraint-denied", auditEvent.Action);
        Assert.Equal(AuditOutcome.Denied, auditEvent.Outcome);
        Assert.Equal("ApiKey", auditEvent.Category);
        // Target is the structured "<commandKind>:<target>" form.
        Assert.Equal("Write:42", auditEvent.Target);
        Assert.NotNull(auditEvent.DetailsJson);
        Assert.Contains("max_write_classification", auditEvent.DetailsJson, StringComparison.Ordinal);
        Assert.Null(auditEvent.CorrelationId);
    }

    /// <summary>A denial carrying a parseable correlation id stores it on the audit record.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task RecordDenialAsync_WithGuidCorrelationId_StoresCorrelationId()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out FakeAuditWriter auditWriter);
        Guid correlationId = Guid.NewGuid();

        await enforcer.RecordDenialAsync(
            identity: null,
            "Read",
            "Secret.Tag",
            new ConstraintFailure("read_scope", "Tag is outside the API key read scope."),
            correlationId.ToString(),
            CancellationToken.None);

        AuditEvent auditEvent = Assert.Single(auditWriter.Events);
        Assert.Equal(correlationId, auditEvent.CorrelationId);
    }

    /// <summary>
    ///     A denial with a non-GUID correlation id leaves the typed audit correlation id null but
    ///     still preserves the raw client correlation id in DetailsJson so it is not lost.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task RecordDenialAsync_WithNonGuidCorrelationId_LeavesCorrelationIdNullButPreservesRawInDetails()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out FakeAuditWriter auditWriter);

        await enforcer.RecordDenialAsync(
            identity: null,
            "Read",
            "Secret.Tag",
            new ConstraintFailure("read_scope", "Tag is outside the API key read scope."),
            "rust-client-Write-7",
            CancellationToken.None);

        AuditEvent auditEvent = Assert.Single(auditWriter.Events);
        Assert.Null(auditEvent.CorrelationId);
        Assert.NotNull(auditEvent.DetailsJson);

        Dictionary<string, string>? details =
            JsonSerializer.Deserialize<Dictionary<string, string>>(auditEvent.DetailsJson);
        Assert.NotNull(details);
        Assert.Equal("rust-client-Write-7", details["clientCorrelationId"]);
    }

    /// <summary>A denial with no identity records the canonical "anonymous" actor.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task RecordDenialAsync_WithoutIdentity_UsesAnonymousActor()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out FakeAuditWriter auditWriter);

        await enforcer.RecordDenialAsync(
            identity: null,
            "Read",
            "Secret.Tag",
            new ConstraintFailure("read_scope", "Tag is outside the API key read scope."),
            correlationId: null,
            CancellationToken.None);

        AuditEvent auditEvent = Assert.Single(auditWriter.Events);
        Assert.Equal("anonymous", auditEvent.Actor);
        Assert.Equal(AuditOutcome.Denied, auditEvent.Outcome);
        Assert.Equal("Read:Secret.Tag", auditEvent.Target);
    }

    /// <summary>Verifies that historized-only constraint requires historized attribute.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WithHistorizedOnly_RequiresRequestedAttributeToBeHistorized()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            ReadHistorizedOnly = true,
        });

        ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
            identity,
            "Pump_001.NonHistorized",
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("read_historized_only", failure.ConstraintName);
    }

    /// <summary>Verifies that alarm-only constraint requires alarm attribute.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WithAlarmOnly_RequiresRequestedAttributeToBeAlarm()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            ReadAlarmOnly = true,
        });

        ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
            identity,
            "Pump_001.PV",
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("read_alarm_only", failure.ConstraintName);
    }

    /// <summary>Verifies that attribute-only constraint fails closed for object tag.</summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WithAttributeOnlyConstraint_FailsClosedForObjectTag()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            ReadHistorizedOnly = true,
        });

        ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
            identity,
            "Pump_001",
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("read_historized_only", failure.ConstraintName);
    }

    /// <summary>
    ///     A bare array attribute address (no trailing <c>[]</c>) resolves through the Galaxy index
    ///     even though arrays are keyed by their suffixed FullTagReference (e.g. "Pump_001.Levels[]").
    ///     Without the <c>[]</c> fallback in ResolveTarget the bare name misses the index and a
    ///     read-constrained key gets a spurious tag_metadata denial for an AddItem it should allow.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WithBareArrayName_ResolvesViaArraySuffixFallback()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            // A read constraint that covers the Pump_001 subtree; the array attribute is inside it.
            ReadTagGlobs = ["Pump_001.*"],
        });

        ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
            identity,
            "Pump_001.Levels",
            CancellationToken.None);

        // Before the fix: bare "Pump_001.Levels" misses the index (keyed "Pump_001.Levels[]") and
        // returns a tag_metadata failure. After the fix: it resolves and is within scope -> null.
        Assert.Null(failure);
    }

    /// <summary>
    ///     A bare non-array name that is genuinely absent from the index still resolves to null:
    ///     the <c>[]</c> probe must not manufacture a false positive for a scalar/missing tag.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WithMissingNonArrayName_StillFailsToResolve()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            ReadTagGlobs = ["Pump_001.*"],
        });

        // "Pump_001.Scalar" is not in the index, and "Pump_001.Scalar[]" is not either, so the
        // suffix probe must not resolve it. A genuinely-unknown name behaves the same.
        ConstraintFailure? missingScalar = await enforcer.CheckReadTagAsync(
            identity,
            "Pump_001.Scalar",
            CancellationToken.None);
        Assert.NotNull(missingScalar);
        Assert.Equal("tag_metadata", missingScalar.ConstraintName);

        ConstraintFailure? unknown = await enforcer.CheckReadTagAsync(
            identity,
            "DoesNotExist_999.Whatever",
            CancellationToken.None);
        Assert.NotNull(unknown);
        Assert.Equal("tag_metadata", unknown.ConstraintName);
    }

    /// <summary>
    ///     The <c>[]</c>-suffix fallback widened *resolution* of a bare array name, not *authorization*:
    ///     a bare array attribute that resolves through the fallback but is outside the key's read scope
    ///     must still be denied with a <c>read_scope</c> failure.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckReadTagAsync_WithBareArrayName_OutOfScope_StillDeniedReadScope()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            // Scope covers a different object, so the resolved array attribute is out of scope.
            ReadTagGlobs = ["Other_001.*"],
        });

        ConstraintFailure? failure = await enforcer.CheckReadTagAsync(
            identity,
            "Pump_001.Levels",
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("read_scope", failure.ConstraintName);
    }

    /// <summary>
    ///     A write against an array handle whose registration carries the suffixed form ("Pump_001.Levels[]")
    ///     resolves through <c>ResolveTarget</c> and is denied with a <c>write_scope</c> failure when the
    ///     array attribute is outside the key's write scope.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckWriteHandleAsync_WithSuffixedArrayRegistration_OutOfScope_StillDeniedWriteScope()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            WriteSubtrees = ["Other/*"],
        });
        GatewaySession session = CreateSession();
        session.TrackCommandReply(
            new MxCommand
            {
                Kind = MxCommandKind.AddItem,
                AddItem = new AddItemCommand
                {
                    ServerHandle = 12,
                    // The worker-bound, suffixed array address is what lands in the registration.
                    ItemDefinition = "Pump_001.Levels[]",
                },
            },
            new MxCommandReply
            {
                ProtocolStatus = ZB.MOM.WW.MxGateway.Server.Grpc.MxAccessGrpcMapper.Ok(),
                AddItem = new AddItemReply { ItemHandle = 70 },
            });

        ConstraintFailure? failure = await enforcer.CheckWriteHandleAsync(
            identity,
            session,
            serverHandle: 12,
            itemHandle: 70,
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("write_scope", failure.ConstraintName);
    }

    /// <summary>
    ///     A write against an in-scope array handle whose registration carries the suffixed form is still
    ///     denied when the array attribute's <c>SecurityClassification</c> exceeds the key's
    ///     <c>MaxWriteClassification</c>, resolved through <c>ResolveTarget</c> via the suffixed address.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation.</returns>
    [Fact]
    public async Task CheckWriteHandleAsync_WithSuffixedArrayRegistration_ClassificationTooHigh_StillDenied()
    {
        ConstraintEnforcer enforcer = CreateEnforcer(out _);
        ApiKeyIdentity identity = CreateIdentity(ApiKeyConstraints.Empty with
        {
            // In scope for the array attribute, but the array's classification (2) exceeds the cap (1).
            WriteTagGlobs = ["Pump_001.*"],
            MaxWriteClassification = 1,
        });
        GatewaySession session = CreateSession();
        session.TrackCommandReply(
            new MxCommand
            {
                Kind = MxCommandKind.AddItem,
                AddItem = new AddItemCommand
                {
                    ServerHandle = 12,
                    ItemDefinition = "Pump_001.Setpoints[]",
                },
            },
            new MxCommandReply
            {
                ProtocolStatus = ZB.MOM.WW.MxGateway.Server.Grpc.MxAccessGrpcMapper.Ok(),
                AddItem = new AddItemReply { ItemHandle = 71 },
            });

        ConstraintFailure? failure = await enforcer.CheckWriteHandleAsync(
            identity,
            session,
            serverHandle: 12,
            itemHandle: 71,
            CancellationToken.None);

        Assert.NotNull(failure);
        Assert.Equal("max_write_classification", failure.ConstraintName);
    }

    private static ConstraintEnforcer CreateEnforcer(out FakeAuditWriter auditWriter)
    {
        auditWriter = new FakeAuditWriter();
        return new ConstraintEnforcer(new StubGalaxyHierarchyCache(CreateEntry()), auditWriter);
    }

    private static ApiKeyIdentity CreateIdentity(ApiKeyConstraints constraints)
    {
        return new ApiKeyIdentity(
            KeyId: "operator01",
            KeyPrefix: "mxgw_operator01",
            DisplayName: "Operator",
            Scopes: new HashSet<string>(StringComparer.Ordinal),
            Constraints: constraints);
    }

    private static GatewaySession CreateSession()
    {
        GatewaySession session = new(
            "session-1",
            "mxaccess",
            "pipe",
            "nonce",
            "operator",
            "client",
            "correlation",
            TimeSpan.FromSeconds(30),
            TimeSpan.FromSeconds(5),
            TimeSpan.FromSeconds(5),
            DateTimeOffset.UtcNow);
        return session;
    }

    private static GalaxyHierarchyCacheEntry CreateEntry()
    {
        IReadOnlyList<GalaxyObject> objects =
        [
            new GalaxyObject
            {
                GobjectId = 1,
                TagName = "Area1",
                ContainedName = "Area1",
            },
            new GalaxyObject
            {
                GobjectId = 2,
                TagName = "Pump_001",
                ContainedName = "Pump",
                ParentGobjectId = 1,
                Attributes =
                {
                    new GalaxyAttribute
                        {
                            AttributeName = "PV",
                            FullTagReference = "Pump_001.PV",
                            SecurityClassification = 2,
                            IsHistorized = true,
                        },
                        new GalaxyAttribute
                        {
                            AttributeName = "Alarm",
                            FullTagReference = "Pump_001.Alarm",
                            IsAlarm = true,
                        },
                        new GalaxyAttribute
                        {
                            AttributeName = "NonHistorized",
                            FullTagReference = "Pump_001.NonHistorized",
                        },
                        new GalaxyAttribute
                        {
                            // Galaxy SQL keys array attributes by their suffixed FullTagReference,
                            // so the index entry is "Pump_001.Levels[]", not the bare name.
                            AttributeName = "Levels",
                            FullTagReference = "Pump_001.Levels[]",
                            IsArray = true,
                        },
                        new GalaxyAttribute
                        {
                            // A second array attribute carrying a non-zero security classification so
                            // the MaxWriteClassification check can be exercised via a suffixed
                            // registration address resolving through ResolveTarget.
                            AttributeName = "Setpoints",
                            FullTagReference = "Pump_001.Setpoints[]",
                            IsArray = true,
                            SecurityClassification = 2,
                        },
                    },
                },
            new GalaxyObject
            {
                GobjectId = 3,
                TagName = "Other_001",
                ContainedName = "Other",
                Attributes =
                {
                    new GalaxyAttribute
                    {
                        AttributeName = "PV",
                        FullTagReference = "Other_001.PV",
                    },
                },
            },
        ];

        return GalaxyHierarchyCacheEntry.Empty with
        {
            Status = GalaxyCacheStatus.Healthy,
            Objects = objects,
            Index = GalaxyHierarchyIndex.Build(objects),
        };
    }

    private sealed class StubGalaxyHierarchyCache(GalaxyHierarchyCacheEntry current) : IGalaxyHierarchyCache
    {
        /// <summary>Gets the current cache entry.</summary>
        public GalaxyHierarchyCacheEntry Current { get; } = current;

        /// <summary>No-op refresh; the stub's <see cref="Current"/> entry never changes.</summary>
        /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public Task RefreshAsync(CancellationToken cancellationToken) => Task.CompletedTask;

        /// <summary>No-op wait; the stub's <see cref="Current"/> entry is already loaded.</summary>
        /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public Task WaitForFirstLoadAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }

    private sealed class FakeAuditWriter : IAuditWriter
    {
        /// <summary>Gets the recorded canonical audit events.</summary>
        public List<AuditEvent> Events { get; } = [];

        /// <summary>Records the audit event in <see cref="Events"/> for later assertions.</summary>
        /// <param name="auditEvent">The audit event to record.</param>
        /// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public Task WriteAsync(AuditEvent auditEvent, CancellationToken cancellationToken = default)
        {
            Events.Add(auditEvent);
            return Task.CompletedTask;
        }
    }
}
