package utils

import (
	"fmt"
	"io/ioutil"
	"path"

	"gopkg.in/yaml.v3"
)

const (
	TestConfig       = "tests/configtest/config.yaml"
	TestSecretConfig = "tests/configtest/secret"
)

func NewConfig(configPath, secretDir string) *Config {
	content, err := ioutil.ReadFile(configPath)
	if err != nil {
		panic(fmt.Sprintf("read config file failed, err= %v", err))
	}

	config := &Config{}
	if err := yaml.Unmarshal(content, config); err != nil {
		panic(fmt.Sprintf("parse config file failed, err= %v", err))
	}

	// read secret config
	readSecret := func(secret string) []byte {
		content, err = ioutil.ReadFile(path.Join(secretDir, secret))
		if err != nil {
			panic(fmt.Sprintf("read secret config %s failed, err= %v", secret, err))
		}
		return content
	}
	config.DSN = string(readSecret("dsn"))
	config.JWTKey = readSecret("jwtKey")
	config.GoogleOAuthAud = string(readSecret("googleOAuthAud"))
	return config
}

type Config struct {
	// URL is the TCMS's base URL. e.g. https://tcms.pingcap.net
	BaseURL   string `yaml:"base-url"`
	RedisAddr string `yaml:"redis-addr"`
	Argo      struct {
		Endpoint string `yaml:"endpoint"`
	} `yaml:"argo"`
	MeiliSearch struct {
		Endpoint string `yaml:"endpoint"`
	} `yaml:"meilisearch"`

	// secret config
	Secret
}

type Secret struct {
	DSN            string `yaml:"-"`
	JWTKey         []byte `yaml:"-"`
	GoogleOAuthAud string `yaml:"-"`
}
