package interceptor

import (
	"context"

	opapiv1beta1 "github.com/tidbcloud/metrics-integration/global/api/integration/openapi/v1beta1"
	consolev1 "github.com/tidbcloud/metrics-integration/global/api/integration/v1"
	"github.com/tidbcloud/metrics-integration/global/internal/infrastructure/account"
	"google.golang.org/grpc"
)

var userCheckerHttpMethodMap = map[string]struct{}{
	consolev1.IntegrationService_CreateIntegration_FullMethodName:      {},
	consolev1.IntegrationService_UpdateIntegration_FullMethodName:      {},
	consolev1.IntegrationService_DeleteIntegration_FullMethodName:      {},
	consolev1.IntegrationService_ValidateDatadogAPIKey_FullMethodName:  {},
	consolev1.IntegrationService_ValidateNewrelicAPIKey_FullMethodName: {},
	consolev1.IntegrationService_ListIntegrations_FullMethodName:       {},
	opapiv1beta1.IntegrationService_CreateIntegration_FullMethodName:   {},
	opapiv1beta1.IntegrationService_DeleteIntegration_FullMethodName:   {},
	opapiv1beta1.IntegrationService_ListIntegrations_FullMethodName:    {},
}

// UserCheckerUnaryServerInterceptor is a gRPC unary server interceptor that checks the user's organization ID, avoid unauthorized cross-tenant operations
func UserCheckerUnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{},
		info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
	) (interface{}, error) {
		if _, ok := userCheckerHttpMethodMap[info.FullMethod]; !ok {
			return handler(ctx, req)
		}

		// OpenAPI remove org and project param, only console api has these two params
		return account.UserCheckerUnaryServerInterceptor()(ctx, req, info, handler)
	}
}
