package config

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/common/constants"
)

func TestRootConfig(t *testing.T) {
	config, err := LoadRootConfig("../../examples/root-config-eks.yaml")
	assert.NoError(t, err)
	assert.NotNil(t, config.APPBoxConfig)
}

func TestLoadRootConfigO11yAgentConfig(t *testing.T) {
	path := filepath.Join(t.TempDir(), "root-config.yaml")
	assert.NoError(t, os.WriteFile(path, []byte(`
o11yAgentNamespace: cp9-dedicated
o11yBizType: cp9-session-1
`), 0o600))

	config, err := LoadRootConfig(path)
	assert.NoError(t, err)
	assert.Equal(t, "cp9-dedicated", config.O11yAgentNamespace)
	assert.Equal(t, "cp9-session-1", config.O11yBizType)
}

func TestSetGlobalConfig(t *testing.T) {
	config, err := LoadRootConfig("../../examples/root-config-eks.yaml")
	assert.NoError(t, err)
	assert.NotNil(t, config.APPBoxConfig)
	assert.Equal(t, constants.DataPlaneAccountNamespace, "dataplane-account")
	config.DataPlaneAccountNamespace = ""
	assert.Equal(t, constants.DataPlaneAccountNamespace, "dataplane-account")
	SetGlobalConfig(config)
	config.DataPlaneAccountNamespace = "regional-server-system"
	SetGlobalConfig(config)
	assert.Equal(t, constants.DataPlaneAccountNamespace, "regional-server-system")
}

func TestIsEnableO11yService(t *testing.T) {
	testData := []struct {
		name     string
		config   RootConfig
		expected bool
	}{
		{
			name: "o11y server enabled",
			config: RootConfig{
				O11yRegionalServiceEndpoint: "http://o11y-regional-server",
			},
			expected: true,
		},
		{
			name: "o11y test server enabled",
			config: RootConfig{
				O11yRegionalServerTestConfig: O11yRegionalServerTestConfig{
					Enable:       true,
					TestEndpoint: "http://o11y-regional-server",
				},
			},
			expected: true,
		},
		{
			name:     "o11y server disabled",
			config:   RootConfig{},
			expected: false,
		},
	}

	for _, data := range testData {
		t.Run(data.name, func(t *testing.T) {
			assert.Equal(t, data.expected, data.config.IsEnableO11yService())
		})
	}
}
