package app

import (
	"encoding/json"
	"os"

	"github.com/rs/zerolog/log"
)

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

type Config struct {
	DBConfig      *DBConfig      `json:"db_config"`
	RegionConfigs []RegionConfig `json:"region_configs"`
	Debug         bool           `json:"debug"`
	GatewayUrl    string         `json:"gateway_url"`
	SSOUrl        string         `json:"sso_url"`
}

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

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

func LoadConfig() *Config {
	configFile := "config/config.json"
	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
	// }
	if err := json.Unmarshal(data, &config); err != nil {
		log.Err(err).Msg("Failed to parse config file")
		return nil
	}
	log.Info().Msgf("config password: %s", config.DBConfig.Password)
	password := os.Getenv("RDB_PASSWORD")
	log.Info().Msgf("RDB_PASSWORD: %s", password)
	log.Info().Msgf("config: %+v", config)
	if password != "" {
		config.DBConfig.Password = password
	}
	// 如果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
}
