package app

import (
	"os"

	"github.com/rs/zerolog/log"
	"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"`
	GatewayUrl    string         `yaml:"gateway_url"`
}

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 {
		log.Err(err).Msgf("Failed to read config file: %s", configFile)
		return nil
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		log.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
}
