using System.Security.Cryptography;
using System.Text;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.LocalDb.Replication;

namespace ZB.MOM.WW.ScadaBridge.Host;

/// <summary>
/// Gates the LocalDb passive sync endpoint. The replication library deliberately leaves
/// inbound authentication to the host — its <c>LocalDbSyncService</c> verifies nothing —
/// so without this interceptor anything that can reach the site node's gRPC port could
/// stream arbitrary rows into the consolidated site database.
/// </summary>
/// <remarks>
/// <para>
/// <b>Scoped by method path.</b> Only calls under
/// <c>/localdb_sync.v1.LocalDbSync/</c> are gated; every other method — notably the
/// existing <c>SiteStream</c> service sharing this listener — passes through untouched.
/// </para>
/// <para>
/// <b>Fail-closed.</b> With no <c>LocalDb:Replication:ApiKey</c> configured, NO sync
/// stream is accepted, authenticated or not. That is the deliberate choice: the
/// alternative — treating "no key" as "no auth required" — would silently expose the
/// endpoint on exactly the default configuration every site node ships with. An operator
/// enabling replication must set the same key on both nodes, which is already required
/// for the initiator to dial out (<c>SyncBackgroundService</c> sends
/// <c>Authorization: Bearer &lt;key&gt;</c>).
/// </para>
/// <para>
/// Comparison is <see cref="CryptographicOperations.FixedTimeEquals"/> over UTF-8 bytes,
/// so a wrong key cannot be recovered byte-by-byte from response timing. Length differences
/// are unavoidably observable and are not sensitive.
/// </para>
/// </remarks>
public sealed class LocalDbSyncAuthInterceptor : Interceptor
{
    private const string ServicePrefix = "/localdb_sync.v1.LocalDbSync/";
    private const string AuthorizationHeader = "authorization";
    private const string BearerPrefix = "Bearer ";

    private readonly IOptions<ReplicationOptions> _options;
    private readonly ILogger<LocalDbSyncAuthInterceptor> _logger;

    /// <summary>Creates the interceptor.</summary>
    /// <param name="options">Replication options; <c>ApiKey</c> is the expected bearer token.</param>
    /// <param name="logger">Logger for denial diagnostics.</param>
    public LocalDbSyncAuthInterceptor(
        IOptions<ReplicationOptions> options,
        ILogger<LocalDbSyncAuthInterceptor> logger)
    {
        ArgumentNullException.ThrowIfNull(options);
        ArgumentNullException.ThrowIfNull(logger);

        _options = options;
        _logger = logger;
    }

    /// <inheritdoc />
    public override Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
        TRequest request,
        ServerCallContext context,
        UnaryServerMethod<TRequest, TResponse> continuation)
    {
        Authorize(context);
        return continuation(request, context);
    }

    /// <inheritdoc />
    public override Task DuplexStreamingServerHandler<TRequest, TResponse>(
        IAsyncStreamReader<TRequest> requestStream,
        IServerStreamWriter<TResponse> responseStream,
        ServerCallContext context,
        DuplexStreamingServerMethod<TRequest, TResponse> continuation)
    {
        Authorize(context);
        return continuation(requestStream, responseStream, context);
    }

    /// <inheritdoc />
    public override Task<TResponse> ClientStreamingServerHandler<TRequest, TResponse>(
        IAsyncStreamReader<TRequest> requestStream,
        ServerCallContext context,
        ClientStreamingServerMethod<TRequest, TResponse> continuation)
    {
        Authorize(context);
        return continuation(requestStream, context);
    }

    /// <inheritdoc />
    public override Task ServerStreamingServerHandler<TRequest, TResponse>(
        TRequest request,
        IServerStreamWriter<TResponse> responseStream,
        ServerCallContext context,
        ServerStreamingServerMethod<TRequest, TResponse> continuation)
    {
        Authorize(context);
        return continuation(request, responseStream, context);
    }

    /// <summary>
    /// Throws <see cref="RpcException"/> with <see cref="StatusCode.PermissionDenied"/> if
    /// this is a sync call that does not carry the configured bearer token. Non-sync calls
    /// return immediately.
    /// </summary>
    private void Authorize(ServerCallContext context)
    {
        if (!context.Method.StartsWith(ServicePrefix, StringComparison.Ordinal))
            return;

        var expected = _options.Value.ApiKey;
        if (string.IsNullOrEmpty(expected))
        {
            _logger.LogWarning(
                "Rejected a LocalDb sync call to {Method}: no LocalDb:Replication:ApiKey is configured, " +
                "so the passive sync endpoint is closed. Configure the same key on both nodes of the pair.",
                context.Method);
            throw new RpcException(new Status(
                StatusCode.PermissionDenied,
                "LocalDb sync is not accepting connections: no API key is configured on this node."));
        }

        var presented = ExtractBearerToken(context.RequestHeaders);
        if (presented is null || !FixedTimeEquals(presented, expected))
        {
            _logger.LogWarning(
                "Rejected a LocalDb sync call to {Method}: {Reason}.",
                context.Method,
                presented is null ? "no bearer token presented" : "bearer token did not match");
            throw new RpcException(new Status(
                StatusCode.PermissionDenied,
                "LocalDb sync authentication failed."));
        }
    }

    private static string? ExtractBearerToken(Metadata headers)
    {
        // gRPC lowercases header keys on the wire; compare case-insensitively anyway so a
        // hand-built Metadata in a test behaves the same as a real request.
        foreach (var entry in headers)
        {
            if (!string.Equals(entry.Key, AuthorizationHeader, StringComparison.OrdinalIgnoreCase))
                continue;

            var value = entry.Value;
            if (value is not null && value.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase))
                return value[BearerPrefix.Length..];
        }

        return null;
    }

    private static bool FixedTimeEquals(string presented, string expected)
        => CryptographicOperations.FixedTimeEquals(
            Encoding.UTF8.GetBytes(presented), Encoding.UTF8.GetBytes(expected));
}
