package grpccorrelation

import (
	"context"
	"testing"

	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/labkit/correlation"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

func getTestUnaryHandler(require *require.Assertions, expCorrelationID, expClientName string) grpc.UnaryHandler {
	return func(ctx context.Context, req interface{}) (interface{}, error) {
		require.Equal(expCorrelationID, correlation.ExtractFromContext(ctx))
		require.Equal(expClientName, correlation.ExtractClientNameFromContext(ctx))
		return nil, nil
	}
}

func TestUnaryServerCorrelationInterceptor(t *testing.T) {
	require := require.New(t)
	correlationID := "CORRELATION_ID"
	clientName := "CLIENT_NAME"

	interceptor := UnaryServerCorrelationInterceptor()

	md := metadata.Pairs(
		metadataCorrelatorKey,
		correlationID,
		metadataClientNameKey,
		clientName,
	)
	ctx := metadata.NewIncomingContext(context.Background(), md)
	_, err := interceptor(
		ctx,
		nil,
		nil,
		getTestUnaryHandler(require, correlationID, clientName),
	)
	require.NoError(err)
}
