package app

import (
	"os"

	"gitlab.com/security-rd/go-pkg/logging"
	"gopkg.in/yaml.v2"
)

const (
	DB_USER     = "ivan"
	DB_PASSWORD = "Mysql-ha@123"
	DB_HOST     = "localhost"
	DB_PORT     = "3306"
	DB_NAME     = "waf"
)

type Config struct {
	DBConfig      *DBConfig      `yaml:"db_config"`
	RegionConfigs []RegionConfig `yaml:"region_configs"`
	Debug         bool           `yaml:"debug"`
}

type DBConfig struct {
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Database string `yaml:"database"`
}

type RegionConfig struct {
	RegionCode     string `yaml:"region_code"`
	ApiServer      string `yaml:"api_server"`
	CAData         string `yaml:"ca_data"`
	Token          string `yaml:"token"`
	ClientCertData string `yaml:"client_cert_data"`
	ClientKeyData  string `yaml:"client_key_data"`
	Insecure       bool   `yaml:"insecure"`
}

func LoadConfig() *Config {
	configFile := "config/config.yaml"
	if envFile := os.Getenv("CONFIG_FILE"); envFile != "" {
		configFile = envFile
	}

	data, err := os.ReadFile(configFile)
	if err != nil {
		logging.Get().Error().Err(err).Msgf("Failed to read config file: %s", configFile)
		return nil
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		logging.Get().Error().Err(err).Msg("Failed to parse config file")
		return nil
	}
	// 如果config.DBConfig为nil，则使用默认值
	if config.DBConfig == nil {
		config.DBConfig = &DBConfig{
			User:     DB_USER,
			Password: DB_PASSWORD,
			Host:     DB_HOST,
			Port:     DB_PORT,
			Database: DB_NAME,
		}
	}

	return &config
}
