package config

import (
	"io/ioutil"
	"path/filepath"

	"github.com/pingcap/errors"
	"gopkg.in/yaml.v2"
)

type Config struct {
	// BaseKubeConfig if it is empty, will use in-Cluster config client
	BaseKubeConfig string `yaml:"baseKubeConfig"`
	// GardenerProjectName is project name in gardener, eg: nightly,staging,prod
	GardenerProjectName *string `yaml:"gardenerProjectName"`
	LogLevel            string  `yaml:"logLevel"`
	// LokiIngressHostName is loki ingress address, if not special, will get the address from logging/loki-mtls-ingress
	LokiIngressHostName string `yaml:"lokiIngressHostName"`
	// LokiStackChartPath is path of loki helm chart address, it contains loki and fluent-bit
	LokiStackChartPath *string `yaml:"lokiStackChartPath"`

	// Filebeat elasticsearch output
	AwsESHost *string `yaml:"awsESHost"`
	AwsESPwd  *string `yaml:"awsESPwd"`
	// Filebeat slow query tidb output
	SlowQueryTiDBHost     *string `yaml:"slowQueryTiDBHost"`
	SlowQueryTiDBUser     *string `yaml:"slowQueryTiDBUser"`
	SlowQueryTiDBPassword *string `yaml:"slowQueryTiDBPassword"`
	SlowQueryTiDBDatabase *string `yaml:"slowQueryTiDBDatabase"`
	SlowQueryTiDBCA       *string `yaml:"slowQueryTiDBCA"`
	SlowQueryTiDBCert     *string `yaml:"slowQueryTiDBCert"`
	SlowQueryTiDBKey      *string `yaml:"slowQueryTiDBKey"`

	// DashboardChartPath is path of kubernetes dashboard chart path
	DashboardChartPath *string `yaml:"dashboardChartPath"`
	// PortalAuth0Issuer and PortalClientID will used for verify portal token in kube-oidc-proxy
	PortalAuth0Issuer *string `yaml:"portalAuth0Issuer"`
	PortalClientID    *string `yaml:"portalClientID"`

	// EventrouterChartPath is path of kubernetes dashboard chart path
	EventrouterChartPath *string `yaml:"eventrouterChartPath"`
}

// InitConfig parse the configuration
func InitConfig(path string) (*Config, error) {
	config := new(Config)
	yamlFile, err := ioutil.ReadFile(filepath.Clean(path))
	if err != nil {
		return config, errors.Annotate(err, "failed to read config file")
	}
	err = yaml.Unmarshal(yamlFile, config)
	if err != nil {
		return config, errors.Annotate(err, "failed to unmarshal config file")
	}

	return config, nil
}

func (c *Config) Validate() error {
	if c.GardenerProjectName == nil {
		return errors.New("must special gardener project name")
	}
	if c.LokiStackChartPath == nil {
		return errors.New("must special loki stack chart path")
	}
	if c.DashboardChartPath == nil {
		return errors.New("must special kubernetes dashboard chart path")
	}
	if c.PortalAuth0Issuer == nil {
		return errors.New("must special portal auth0 issuer")
	}
	if c.PortalClientID == nil {
		return errors.New("must special portal clientID")
	}

	return nil
}
