using Grpc.Core;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.LocalDb.Replication;
using ZB.MOM.WW.ScadaBridge.Host;

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

/// <summary>
/// LocalDb Phase 1 (Task 8) — the passive sync endpoint's inbound gate.
/// </summary>
/// <remarks>
/// The replication library's <c>LocalDbSyncService</c> verifies nothing; inbound auth is
/// explicitly the host's job. Without this interceptor, anything able to reach a site
/// node's gRPC port could stream arbitrary rows straight into the consolidated site
/// database — including into <c>OperationTracking</c>, which central reconciles from.
/// </remarks>
public class LocalDbSyncAuthInterceptorTests
{
    private const string SyncMethod = "/localdb_sync.v1.LocalDbSync/Sync";
    private const string SiteStreamMethod = "/scadabridge.SiteStream/Connect";

    private static LocalDbSyncAuthInterceptor CreateInterceptor(string? apiKey)
        => new(
            Options.Create(new ReplicationOptions { ApiKey = apiKey }),
            NullLogger<LocalDbSyncAuthInterceptor>.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>
    /// Minimal <see cref="ServerCallContext"/> carrying just a method name and request
    /// headers — the only two things the interceptor reads.
    /// </summary>
    /// <remarks>
    /// Hand-rolled rather than using <c>Grpc.Core.Testing.TestServerCallContext</c>: that
    /// type ships in the retired native <c>Grpc.Core</c> package and does not exist on the
    /// grpc-dotnet stack this solution runs on. Pulling in the dead package to get one
    /// test helper would be a worse trade than these few overrides.
    /// </remarks>
    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;
    }

    /// <summary>Invokes the interceptor's unary path with a trivial continuation.</summary>
    private static Task<string> Invoke(
        LocalDbSyncAuthInterceptor interceptor, ServerCallContext context)
        => interceptor.UnaryServerHandler<string, string>(
            "request", context, (_, _) => Task.FromResult("ok"));

    [Fact]
    public async Task NonSyncMethod_PassesThrough_EvenWithNoKeyConfigured()
    {
        // The interceptor is registered on the shared site AddGrpc pipeline, so it sees
        // every call. It must be scoped strictly to the sync service — gating SiteStream
        // would break site↔central communication outright.
        var interceptor = CreateInterceptor(apiKey: null);
        var context = CreateContext(SiteStreamMethod, authorizationHeader: null);

        Assert.Equal("ok", await Invoke(interceptor, context));
    }

    [Fact]
    public async Task SyncMethod_WithNoKeyConfigured_IsDenied_EvenWithABearerToken()
    {
        // Fail-closed. "No key configured" is the DEFAULT every site node ships with, so
        // treating it as "no auth required" would silently expose the endpoint on exactly
        // the configuration that is most common. Presenting a token must not help.
        var interceptor = CreateInterceptor(apiKey: null);
        var context = CreateContext(SyncMethod, "Bearer anything-at-all");

        var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
        Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
    }

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

        var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
        Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
    }

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

        var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
        Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
    }

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

        Assert.Equal("ok", await Invoke(interceptor, context));
    }

    [Fact]
    public async Task SyncMethod_WithCorrectKey_ButNoBearerScheme_IsDenied()
    {
        // A raw key with no "Bearer " prefix is not what SyncBackgroundService sends, and
        // accepting it would widen the accepted credential shape for no reason.
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(SyncMethod, "the-shared-key");

        var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
        Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
    }

    [Fact]
    public async Task SyncMethod_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(SyncMethod, "Bearer the-shared-ke");

        var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
        Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
    }

    [Fact]
    public async Task DuplexStreaming_IsGated_BecauseThatIsHowSyncActuallyRuns()
    {
        // The sync RPC is a bidirectional stream. Gating only the unary path would leave
        // the real endpoint wide open while every unary test still passed.
        var interceptor = CreateInterceptor("the-shared-key");
        var context = CreateContext(SyncMethod, "Bearer the-wrong-key");

        var ex = await Assert.ThrowsAsync<RpcException>(() =>
            interceptor.DuplexStreamingServerHandler<string, string>(
                requestStream: null!,
                responseStream: null!,
                context,
                (_, _, _) => Task.CompletedTask));

        Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
    }
}
