package config

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

	. "github.com/onsi/gomega"
	"gopkg.in/yaml.v2"
)

func TestLoadFromPath(t *testing.T) {
	t.Run("default value", func(t *testing.T) {
		g := NewGomegaWithT(t)
		conf := DiagConfig{}
		content, err := yaml.Marshal(conf)
		g.Expect(err).Should(BeNil())
		path := "test_diag_config.yaml"
		os.WriteFile(path, content, fs.ModePerm)
		defer os.Remove(path)

		result := LoadFromPath(path)
		g.Expect(result).Should(Equal(&DiagConfig{
			Enable:   false,
			Provider: ProviderAWS,
			Region:   DefaultRegion,
			Task: TaskConfig{
				Interval:                  DefaultTaskSyncInterval,
				Bucket:                    DefaultBucket,
				TaskFilePrefix:            DefaultTaskFilePrefix,
				CatalogPath:               DefaultCatalogPath,
				ClusterMetaFilePrefix:     DefaultClusterMetaPrefix,
				ServerlessVIPListPath:     DefaultServerlessVIPListPath,
				ServerlessSpendLimitsPath: DefaultServerlessSpendLimitsPath,
				ServerlessSkuPricePath:    DefaultServerlessSkuPricePath,
			},
			DiagEngine: DiagEngineConfig{
				Interval:          DefaultDiagEngineSyncInterval,
				Name:              DefaultDiagEngineName,
				Namespace:         DefaultDiagEngineNamespace,
				MaxTasksPerEngine: DefaultMaxTasksPerEngine,
				MinTasksPerEngine: DefaultMinTasksPerEngine,
			},
		}))
	})
	t.Run("load from file", func(t *testing.T) {
		g := NewGomegaWithT(t)
		conf := DiagConfig{
			Enable:   true,
			Provider: ProviderAWS,
			Region:   "test-region",
			Task: TaskConfig{
				Interval:                  10 * time.Minute,
				Bucket:                    "test-bucket",
				TaskFilePrefix:            "test-prefix",
				CatalogPath:               "test-path",
				ClusterMetaFilePrefix:     "test-meta-prefix",
				ServerlessVIPListPath:     "test-vip-list-path",
				ServerlessSpendLimitsPath: "test-spend-limits-path",
				ServerlessSkuPricePath:    "test-sku-price-path",
			},
			DiagEngine: DiagEngineConfig{
				Interval:          2 * time.Minute,
				Name:              "test-name",
				Namespace:         "test-namespace",
				MaxTasksPerEngine: 10,
				MinTasksPerEngine: 2,
			},
		}
		content, err := yaml.Marshal(conf)
		g.Expect(err).Should(BeNil())
		path := "test_diag_config_load.yaml"
		os.WriteFile(path, content, fs.ModePerm)
		defer os.Remove(path)

		result := LoadFromPath(path)
		g.Expect(result).Should(Equal(&conf))
	})

	t.Run("path not exist", func(t *testing.T) {
		g := NewGomegaWithT(t)
		path := "test_diag_config_not_exist.yaml"
		result := LoadFromPath(path)
		g.Expect(result).Should(Equal(&DiagConfig{Enable: false}))
	})
}
