using Grpc.Core;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;

namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;

/// <summary>
///     Per-cluster mesh Phase 3 (Task 3) — the config-serve artifact endpoint's inbound gate.
/// </summary>
/// <remarks>
///     The <c>DeploymentArtifactService</c> streams a driver node the exact configuration it will
///     boot on. Anything able to reach central's serve port could otherwise pull the whole deployed
///     config, so the endpoint is gated by a shared bearer key, fail-closed, constant-time — the
///     same contract as <see cref="LocalDbSyncAuthInterceptor"/>, scoped to a different service path.
/// </remarks>
public sealed class ConfigServeAuthInterceptorTests
{
    private const string FetchMethod = "/deployment_artifact.v1.DeploymentArtifactService/Fetch";
    private const string OtherMethod = "/localdb_sync.v1.LocalDbSync/Sync";

    private static ConfigServeAuthInterceptor CreateInterceptor(string? apiKey)
        => new(
            Options.Create(new ConfigServeOptions { ApiKey = apiKey ?? string.Empty }),
            NullLogger<ConfigServeAuthInterceptor>.Instance);

    private static ServerCallContext CreateContext(string method, string? authorizationHeader)
    {
        var headers = new Metadata();
        if (authorizationHeader is not null)
            headers.Add("authorization", authorizationHeader);

        return new FakeServerCallContext(method, headers);
    }

    /// <summary>Invokes the interceptor's server-streaming path (how <c>Fetch</c> actually runs).</summary>
    private static Task Invoke(ConfigServeAuthInterceptor interceptor, ServerCallContext context)
        => interceptor.ServerStreamingServerHandler<string, string>(
            "request", responseStream: null!, context, (_, _, _) => Task.CompletedTask);

    [Fact]
    public async Task NonServeMethod_PassesThrough_EvenWithNoKeyConfigured()
    {
        // The interceptor shares the AddGrpc pipeline with the LocalDb sync interceptor, so it sees
        // every call. It must be scoped strictly to the artifact service — a sync call is not its
        // business.
        var interceptor = CreateInterceptor(apiKey: null);
        var context = CreateContext(OtherMethod, authorizationHeader: null);

        await Invoke(interceptor, context); // no throw
    }

    [Fact]
    public async Task FetchMethod_WithNoKeyConfigured_IsDenied_EvenWithABearerToken()
    {
        // Fail-closed. "No key configured" is the DEFAULT — treating it as "no auth required" would
        // expose the deployed config on exactly the shape most nodes ship with. A token must not help.
        var interceptor = CreateInterceptor(apiKey: null);
        var context = CreateContext(FetchMethod, "Bearer anything-at-all");

        var ex = await Should.ThrowAsync<RpcException>(() => Invoke(interceptor, context));
        ex.StatusCode.ShouldBe(StatusCode.Unauthenticated);
    }

    [Fact]
    public async Task FetchMethod_WithNoBearerToken_IsDenied()
    {
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(FetchMethod, authorizationHeader: null);

        var ex = await Should.ThrowAsync<RpcException>(() => Invoke(interceptor, context));
        ex.StatusCode.ShouldBe(StatusCode.Unauthenticated);
    }

    [Fact]
    public async Task FetchMethod_WithWrongBearerToken_IsDenied()
    {
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(FetchMethod, "Bearer the-wrong-key");

        var ex = await Should.ThrowAsync<RpcException>(() => Invoke(interceptor, context));
        ex.StatusCode.ShouldBe(StatusCode.Unauthenticated);
    }

    [Fact]
    public async Task FetchMethod_WithCorrectBearerToken_PassesThrough()
    {
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(FetchMethod, "Bearer the-shared-key");

        await Invoke(interceptor, context); // no throw
    }

    [Fact]
    public async Task FetchMethod_TokenComparison_IsNotAPrefixMatch()
    {
        // A prefix/StartsWith comparison would accept a truncated key and make the secret
        // recoverable one character at a time.
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(FetchMethod, "Bearer the-shared-ke");

        var ex = await Should.ThrowAsync<RpcException>(() => Invoke(interceptor, context));
        ex.StatusCode.ShouldBe(StatusCode.Unauthenticated);
    }

    [Fact]
    public async Task UnaryPath_IsAlsoGated()
    {
        // Fetch is server-streaming today, but gating only that path would leave any future unary
        // method on the same service open. Gate every handler shape.
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(FetchMethod, "Bearer the-wrong-key");

        var ex = await Should.ThrowAsync<RpcException>(() =>
            interceptor.UnaryServerHandler<string, string>(
                "request", context, (_, _) => Task.FromResult("ok")));

        ex.StatusCode.ShouldBe(StatusCode.Unauthenticated);
    }

    /// <summary>
    ///     Minimal <see cref="ServerCallContext"/> carrying just a method name and request headers —
    ///     the only two things the interceptor reads. Hand-rolled because
    ///     <c>Grpc.Core.Testing.TestServerCallContext</c> ships only in the retired native package.
    /// </summary>
    private sealed class FakeServerCallContext(string method, Metadata requestHeaders)
        : ServerCallContext
    {
        protected override string MethodCore => method;
        protected override string HostCore => "localhost";
        protected override string PeerCore => "ipv4:127.0.0.1:12345";
        protected override DateTime DeadlineCore => DateTime.UtcNow.AddMinutes(1);
        protected override Metadata RequestHeadersCore => requestHeaders;
        protected override CancellationToken CancellationTokenCore => CancellationToken.None;
        protected override Metadata ResponseTrailersCore { get; } = [];
        protected override Status StatusCore { get; set; }
        protected override WriteOptions? WriteOptionsCore { get; set; }

        protected override AuthContext AuthContextCore { get; } =
            new(null, new Dictionary<string, List<AuthProperty>>());

        protected override ContextPropagationToken CreatePropagationTokenCore(
            ContextPropagationOptions? options)
            => throw new NotSupportedException();

        protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders)
            => Task.CompletedTask;
    }
}
