package controller

import (
	"context"
	"testing"

	"dataservices/commons/config"
	"dataservices/commons/constants"

	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/dataservices/idl/pbgen/proto/dataapi"
)

func TestNewExecutorDispatchStrategy(t *testing.T) {
	cfg := config.Global()
	oldDeployMode := cfg.ServerConf.DeployMode
	oldProvider := cfg.ServerlessConf.Provider
	defer func() {
		cfg.ServerConf.DeployMode = oldDeployMode
		cfg.ServerlessConf.Provider = oldProvider
	}()

	cfg.ServerConf.DeployMode = "region"
	cfg.ServerlessConf.Provider = constants.ClusterCloudProviderAliCloud
	require.IsType(t, SingleExecutorDispatchStrategy{}, NewExecutorDispatchStrategy())

	cfg.ServerlessConf.Provider = constants.ClusterCloudProviderAWS
	require.IsType(t, RedisSessionDispatchStrategy{}, NewExecutorDispatchStrategy())
}

func TestSingleExecutorDispatchStrategy(t *testing.T) {
	strategy := SingleExecutorDispatchStrategy{}

	execReq := &dataapi.BasicEndpointReqV2{SessionId: "s1"}
	closeReq := &dataapi.CloseSessionReq{SessionId: "s1"}

	require.NoError(t, strategy.PrepareExecReq(context.Background(), execReq))
	require.NoError(t, strategy.PrepareCloseReq(context.Background(), closeReq))
	require.Nil(t, strategy.ExecCallOptions(execReq))
	require.Nil(t, strategy.CloseCallOptions(closeReq))
}

func TestRedisSessionDispatchStrategyCallOptions(t *testing.T) {
	strategy := RedisSessionDispatchStrategy{}
	execReq := &dataapi.BasicEndpointReqV2{
		SessionId: "s1",
		Source:    "exec_endpoint",
		SessionItem: &dataapi.SessionItem{
			ExecutorEndpoint: "127.0.0.1:10000",
		},
	}
	closeReq := &dataapi.CloseSessionReq{
		SessionId: "s1",
		SessionItem: &dataapi.SessionItem{
			ExecutorEndpoint: "127.0.0.1:10000",
		},
	}

	require.Len(t, strategy.ExecCallOptions(execReq), 2)
	require.Len(t, strategy.CloseCallOptions(closeReq), 1)
}
