package config

import (
	"os"
)

type Config struct {
	Server   ServerConfig
	Database DatabaseConfig
	Redis    RedisConfig
	JWT      JWTConfig
	Wechat   WechatConfig
	Admin    AdminConfig
}

type ServerConfig struct {
	Port        string
	Env         string
	CORSOrigins string
}

type DatabaseConfig struct {
	Type     string
	Host     string
	Port     string
	User     string
	Password string
	Name     string
}

type RedisConfig struct {
	Host     string
	Port     string
	Password string
	DB       int
}

type JWTConfig struct {
	Secret string
}

type WechatConfig struct {
	AppID     string
	AppSecret string
	PayKey    string
	MchID     string
}

// AdminConfig 管理后台配置
type AdminConfig struct {
	// Password 管理员登录密码；为空时禁用后台登录
	Password string
}

func Load() *Config {
	return &Config{
		Server: ServerConfig{
			Port:        getEnv("SERVER_PORT", "8080"),
			Env:         getEnv("SERVER_ENV", "development"),
			CORSOrigins: getEnv("CORS_ORIGINS", ""),
		},
		Database: DatabaseConfig{
			Type:     getEnv("DB_TYPE", "mysql"),
			Host:     getEnv("DB_HOST", "localhost"),
			Port:     getEnv("DB_PORT", "3306"),
			User:     getEnv("DB_USER", "root"),
			Password: getEnv("DB_PASSWORD", ""),
			Name:     getEnv("DB_NAME", "lunar"),
		},
		Redis: RedisConfig{
			Host:     getEnv("REDIS_HOST", "localhost"),
			Port:     getEnv("REDIS_PORT", "6379"),
			Password: getEnv("REDIS_PASSWORD", ""),
			DB:       0,
		},
		JWT: JWTConfig{
			Secret: getEnv("JWT_SECRET", "your-secret-key"),
		},
		Wechat: WechatConfig{
			AppID:     getEnv("MINI_APP_ID", ""),
			AppSecret: getEnv("MINI_APP_SECRET", ""),
			PayKey:    getEnv("WECHAT_PAY_APIKEY", ""),
			MchID:     getEnv("WECHAT_PAY_MCHID", ""),
		},
		Admin: AdminConfig{
			Password: getEnv("ADMIN_PASSWORD", ""),
		},
	}
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}
