package k8s

import (
	"sync"

	validation "github.com/Thearas/ozzo-validation/v4"
)

var (
	config Config
	mu     sync.Mutex
)

type Config struct {
	TiDBCluster            TiDBClusterConfig      `yaml:"tidbCluster"`
	MySQLCluster           MySQLClusterConfig     `yaml:"mysqlCluster"`
	TiDBCloudClusterConfig TiDBCloudClusterConfig `yaml:"tidbCloudCluster"`
	Images                 Images                 `yaml:"images"`
}

func (c Config) Validate() error {
	return validation.ValidateStruct(&c,
		validation.Field(&c.TiDBCluster),
		validation.Field(&c.MySQLCluster),
		validation.Field(&c.TiDBCloudClusterConfig),
		validation.Field(&c.Images),
	)
}

type Images struct {
	SDKServer string `yaml:"sdkServer"`
	TCSetup   string `yaml:"tcSetup"`
}

func (i Images) Validate() error {
	return validation.ValidateStruct(&i,
		validation.Field(&i.SDKServer, validation.Required),
		validation.Field(&i.TCSetup, validation.Required),
	)
}

type TiDBClusterConfig struct {
	SpecValidator *TiDBClusterSpecValidator   `yaml:"validator"`
	ReadyCheck    TiDBClusterReadyCheckConfig `yaml:"readyCheck"`
}

type TiDBCloudClusterConfig struct {
	ReadyCheck TiDBCloudClusterReadyCheckConfig `yaml:"readyCheck"`
}

type MySQLClusterConfig struct {
	ReadyCheck MySQLClusterReadyCheckConfig `yaml:"readyCheck"`
}

type MySQLClusterReadyCheckConfig struct {
	PingDB bool `yaml:"pingDB"`
}

type TiDBClusterSpecValidator struct {
	TcValidatorURL string `yaml:"url"`
}

type TiDBClusterReadyCheckConfig struct {
	PingDB      bool `yaml:"pingDB"`
	DialDrainer bool `yaml:"dialDrainer"`
}

type TiDBCloudClusterReadyCheckConfig struct {
	PingDB bool `yaml:"pingDB"`
}

func defaultConfig() Config {
	return Config{
		TiDBCluster:            TiDBClusterConfig{ReadyCheck: TiDBClusterReadyCheckConfig{PingDB: true}},
		MySQLCluster:           MySQLClusterConfig{ReadyCheck: MySQLClusterReadyCheckConfig{PingDB: true}},
		TiDBCloudClusterConfig: TiDBCloudClusterConfig{ReadyCheck: TiDBCloudClusterReadyCheckConfig{PingDB: true}},
		Images: Images{
			SDKServer: "hub.pingcap.net/qa/sdkserver:latest",
			TCSetup:   "hub.pingcap.net/qa/rms-tc-setup:latest",
		},
	}
}

func SetConfig(c Config) {
	mu.Lock()
	defer mu.Unlock()
	config = c
}

func init() {
	config = defaultConfig()
}
