package config

import (
	"os"
	"strconv"
)

type Config struct {
	AppEnv        string
	AppAddr       string
	MySQLDSN      string
	RedisAddr     string
	RedisPassword string
	RedisDB       int
	JWTSecret     string
	Storage       StorageConfig
	SMS           SMSConfig
	Realname      RealnameConfig
	Payment       PaymentConfig
	Log           LogConfig
}

type StorageConfig struct {
	Endpoint        string
	Bucket          string
	AccessKeyID     string
	SecretAccessKey string
}

type SMSConfig struct {
	Provider                string
	AliyunAccessKeyID       string
	AliyunAccessKeySecret   string
	AliyunEndpoint          string
	AliyunSignName          string
	AliyunLoginTemplateCode string
}

type RealnameConfig struct {
	Provider           string
	CloudMarketURL     string
	CloudMarketAppCode string
}

type PaymentConfig struct {
	Provider string
	Leshua   LeshuaPaymentConfig
}

type LeshuaPaymentConfig struct {
	GatewayURL string
	MerchantID string
	SignKey    string
	NotifyKey  string
	NotifyURL  string
	JumpURL    string
	PayWay     string
	JSPayFlag  string
	SignType   string
}

type LogConfig struct {
	Level         string
	Dir           string
	EnableConsole bool
	EnableFile    bool
}

func Load() Config {
	return Config{
		AppEnv:        getEnv("APP_ENV", "development"),
		AppAddr:       getEnv("APP_ADDR", ":8080"),
		MySQLDSN:      getEnv("MYSQL_DSN", "hfb:secret@tcp(127.0.0.1:3306)/hfb_sys?charset=utf8mb4&parseTime=True&loc=Local"),
		RedisAddr:     getEnv("REDIS_ADDR", "127.0.0.1:6379"),
		RedisPassword: getEnv("REDIS_PASSWORD", ""),
		RedisDB:       getEnvInt("REDIS_DB", 0),
		JWTSecret:     getEnv("JWT_SECRET", "change-me"),
		Storage: StorageConfig{
			Endpoint:        getEnv("STORAGE_ENDPOINT", "http://localhost:9000"),
			Bucket:          getEnv("STORAGE_BUCKET", "hfb-sys"),
			AccessKeyID:     getEnv("STORAGE_ACCESS_KEY_ID", "minioadmin"),
			SecretAccessKey: getEnv("STORAGE_SECRET_ACCESS_KEY", "minioadmin"),
		},
		SMS: SMSConfig{
			Provider:                getEnv("SMS_PROVIDER", "mock"),
			AliyunAccessKeyID:       getEnv("ALIYUN_ACCESS_KEY_ID", ""),
			AliyunAccessKeySecret:   getEnv("ALIYUN_ACCESS_KEY_SECRET", ""),
			AliyunEndpoint:          getEnv("ALIYUN_SMS_ENDPOINT", "dysmsapi.aliyuncs.com"),
			AliyunSignName:          getEnv("ALIYUN_SMS_SIGN_NAME", ""),
			AliyunLoginTemplateCode: getEnv("ALIYUN_SMS_LOGIN_TEMPLATE_CODE", ""),
		},
		Realname: RealnameConfig{
			Provider:           getEnv("REALNAME_PROVIDER", "mock"),
			CloudMarketURL:     getEnv("REALNAME_CLOUDMARKET_URL", "https://sinocheck2.market.alicloudapi.com/fortest/ttttt"),
			CloudMarketAppCode: getEnv("REALNAME_CLOUDMARKET_APPCODE", ""),
		},
		Payment: PaymentConfig{
			Provider: getEnv("PAYMENT_PROVIDER", "mock"),
			Leshua: LeshuaPaymentConfig{
				GatewayURL: getEnv("LESHUA_GATEWAY_URL", "https://t-paygate.lepass.cn/cgi-bin/lepos_pay_gateway.cgi"),
				MerchantID: getEnv("LESHUA_MERCHANT_ID", ""),
				SignKey:    getEnv("LESHUA_SIGN_KEY", ""),
				NotifyKey:  getEnv("LESHUA_NOTIFY_KEY", ""),
				NotifyURL:  getEnv("LESHUA_NOTIFY_URL", ""),
				JumpURL:    getEnv("LESHUA_JUMP_URL", ""),
				PayWay:     getEnv("LESHUA_PAY_WAY", "ZFBZF"),
				JSPayFlag:  getEnv("LESHUA_JSPAY_FLAG", "2"),
				SignType:   getEnv("LESHUA_SIGN_TYPE", "MD5"),
			},
		},
		Log: LogConfig{
			Level:         getEnv("LOG_LEVEL", "info"),
			Dir:           getEnv("LOG_DIR", "logs"),
			EnableConsole: getEnvBool("LOG_ENABLE_CONSOLE", true),
			EnableFile:    getEnvBool("LOG_ENABLE_FILE", true),
		},
	}
}

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

func getEnvInt(key string, fallback int) int {
	value := os.Getenv(key)
	if value == "" {
		return fallback
	}
	parsed, err := strconv.Atoi(value)
	if err != nil {
		return fallback
	}
	return parsed
}

func getEnvBool(key string, fallback bool) bool {
	value := os.Getenv(key)
	if value == "" {
		return fallback
	}
	parsed, err := strconv.ParseBool(value)
	if err != nil {
		return fallback
	}
	return parsed
}
