package com.zb.mom.ww.mxgateway.client;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;

/**
 * gRPC client interceptor that attaches the {@code authorization: Bearer ...}
 * header carrying the gateway API key. A blank or {@code null} key disables
 * the interceptor so unauthenticated calls pass through unchanged.
 */
public final class MxGatewayAuthInterceptor implements ClientInterceptor {
    static final Metadata.Key<String> AUTHORIZATION_HEADER =
            Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);

    private final String apiKey;

    /**
     * Creates a new interceptor using the supplied API key.
     *
     * @param apiKey gateway API key; {@code null} or blank disables the interceptor
     */
    public MxGatewayAuthInterceptor(String apiKey) {
        this.apiKey = apiKey == null ? "" : apiKey;
    }

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
            MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
        ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
        if (apiKey.isBlank()) {
            return call;
        }

        return new ForwardingClientCall.SimpleForwardingClientCall<>(call) {
            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                headers.put(AUTHORIZATION_HEADER, "Bearer " + apiKey);
                super.start(responseListener, headers);
            }
        };
    }
}
