package configs

import (
	"io/fs"
	"os"
	"testing"

	"github.com/tidbcloud/observability/pkg/common/structs"
	"gopkg.in/yaml.v3"

	"github.com/stretchr/testify/assert"
)

func TestLoadMonitorSpec(t *testing.T) {
	t.Run("normal", func(t *testing.T) {
		monitorSpecs := make(map[string]structs.MonitorSpec)

		monitorSpecs["spec1"] = structs.MonitorSpec{
			Cpu:            "2",
			Memory:         "200Mi",
			InitialStorage: "222Gi",
		}
		monitorSpecs["spec2"] = structs.MonitorSpec{
			Cpu:            "4",
			Memory:         "222Mi",
			InitialStorage: "666Gi",
			OverSell:       0.5,
		}

		content, err := yaml.Marshal(monitorSpecs)
		assert.NoError(t, err)
		path := "test_specs.yaml"
		os.WriteFile(path, content, fs.ModePerm)
		defer os.Remove(path)

		result := LoadMonitorSpec(path)
		assert.NotEmpty(t, result)
		assert.Equal(t, 2, len(result))
		assert.Equal(t, "200Mi", result["spec1"].Memory)
		assert.Equal(t, 0.0, result["spec1"].OverSell)
		assert.Equal(t, 0.5, result["spec2"].OverSell)
	})
	t.Run("content", func(t *testing.T) {
		c := "    t1g.micro:\n      cpu: 0.5\n      memory: 2Gi\n      initialStorage: 32Gi\n    t1g.small:\n      cpu: 1\n      memory: 4Gi\n      initialStorage: 64Gi\n      isDefault: true\n    t1g.medium:\n      cpu: 2\n      memory: 8Gi\n      initialStorage: 128Gi\n    t1g.large:\n      cpu: 4\n      memory: 16Gi\n      initialStorage: 256Gi\n    t1g.xlarge:\n      cpu: 8\n      memory: 32Gi\n      initialStorage: 512Gi\n    t1g.2xlarge:\n      cpu: 16\n      memory: 64Gi\n      initialStorage: 1024Gi"
		content := map[string]structs.MonitorSpec{}
		err := yaml.Unmarshal([]byte(c), content)
		assert.NoError(t, err)
		assert.NotEmpty(t, content)
		assert.Equal(t, "0.5", content["t1g.micro"].Cpu)
		assert.NotNil(t, content["t1g.micro"].InitialStorage)
	})
	t.Run("invalid file", func(t *testing.T) {
		assert.Panics(t, func() {
			LoadMonitorSpec("invalid")
		})
	})
}
