package configs

import (
	"context"
	"sync"

	"github.com/jinzhu/configor"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

var (
	initConfigOnce sync.Once
	config         *Config
	configPath     = "/etc/dbaas/config.yaml"
)

func SetConfigPath(path string) {
	if path != "" {
		configPath = path
	}
}

type Config struct {
	DBDSN          string `yaml:"db_dsn"`
	AccountSvcAddr string `yaml:"account_svc_addr" required:"true"`
	CMSvcAddr      string `yaml:"cm_svc_addr" required:"true"`
	ACLSvcAddr     string `yaml:"acl_svc_addr" required:"true"`
}

func GetConfig() *Config {
	initConfigOnce.Do(func() {
		config = &Config{}
		ctx := context.TODO()

		if err := configor.Load(config, configPath); err != nil {
			tilog.Error(ctx, "failed to load config from file", zap.Error(err), zap.String("path", configPath))
		}
	})

	return config
}
