package runtimeapi

import (
	"context"
	"testing"

	"github.com/nexuscrm/kernel/pkg/perftiming"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/pingcap-inc/nexuscrm-api-host/runtimegrpc"
	"google.golang.org/grpc/metadata"
)

func TestRuntimeRequestContextInterceptorBindsTransportCorrelation(t *testing.T) {
	ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
		runtimegrpc.RequestIDMetadataKey, "inspection-123",
	))
	var got string
	_, err := runtimeRequestContextInterceptor()(ctx, nil, nil, func(handlerCtx context.Context, _ any) (any, error) {
		got, _ = handlerCtx.Value(constants.ContextKeyRequestID).(string)
		return nil, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	if got != "inspection-123" {
		t.Fatalf("request ID = %q, want inspection-123", got)
	}
}

func TestRuntimeSQLDiagnosticsBindsCorrelationAndPerfTiming(t *testing.T) {
	ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
		runtimegrpc.RequestIDMetadataKey, "sql-inspection-123",
	))
	var gotRequestID string
	var enabled bool
	_, err := runtimeSQLDiagnosticsInterceptor(true, nil)(ctx, nil, nil, func(handlerCtx context.Context, _ any) (any, error) {
		gotRequestID, _ = handlerCtx.Value(constants.ContextKeyRequestID).(string)
		enabled = perftiming.Enabled(handlerCtx)
		return nil, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	if gotRequestID != "sql-inspection-123" || !enabled {
		t.Fatalf("diagnostics context = request %q enabled %t", gotRequestID, enabled)
	}
}

func TestRuntimeSQLDiagnosticsDisabledDoesNotEnablePerfTiming(t *testing.T) {
	var enabled bool
	_, err := runtimeSQLDiagnosticsInterceptor(false, nil)(context.Background(), nil, nil, func(handlerCtx context.Context, _ any) (any, error) {
		enabled = perftiming.Enabled(handlerCtx)
		return nil, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	if enabled {
		t.Fatal("SQL diagnostics enabled without operator opt-in")
	}
}

func TestRuntimeRequestContextInterceptorDoesNotBindAmbiguousCorrelation(t *testing.T) {
	ctx := metadata.NewIncomingContext(context.Background(), metadata.MD{
		runtimegrpc.RequestIDMetadataKey: []string{"inspection-1", "inspection-2"},
	})
	var got any
	_, err := runtimeRequestContextInterceptor()(ctx, nil, nil, func(handlerCtx context.Context, _ any) (any, error) {
		got = handlerCtx.Value(constants.ContextKeyRequestID)
		return nil, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	if got != nil {
		t.Fatalf("ambiguous request ID was bound: %#v", got)
	}
}
