package wallet

import (
	"strings"

	"hyapp/pkg/appcode"
)

// ExternalRechargeConfig 保存 H5 外部充值需要公开给业务链路的运行配置。
type ExternalRechargeConfig struct {
	USDTTRC20Enabled   bool
	USDTTRC20Address   string
	USDTTRC20Addresses map[string]string
	USDTBEP20Enabled   bool
	USDTBEP20Address   string
	USDTBEP20Addresses map[string]string
	MifaPayNotifyURL   string
	MifaPayReturnURL   string
	V5PayNotifyURL     string
	V5PayReturnURL     string
}

func normalizeExternalRechargeConfig(config ExternalRechargeConfig) ExternalRechargeConfig {
	config.USDTTRC20Address = strings.TrimSpace(config.USDTTRC20Address)
	config.USDTTRC20Addresses = normalizeRuntimeRechargeAddressMap(config.USDTTRC20Addresses)
	config.USDTBEP20Address = strings.TrimSpace(config.USDTBEP20Address)
	config.USDTBEP20Addresses = normalizeRuntimeRechargeAddressMap(config.USDTBEP20Addresses)
	config.MifaPayNotifyURL = strings.TrimSpace(config.MifaPayNotifyURL)
	config.MifaPayReturnURL = strings.TrimSpace(config.MifaPayReturnURL)
	config.V5PayNotifyURL = strings.TrimSpace(config.V5PayNotifyURL)
	config.V5PayReturnURL = strings.TrimSpace(config.V5PayReturnURL)
	return config
}

func (config ExternalRechargeConfig) usdtTRC20AddressForApp(app string) string {
	return firstNonEmpty(config.USDTTRC20Addresses[appcode.Normalize(app)], config.USDTTRC20Address)
}

func (config ExternalRechargeConfig) usdtBEP20AddressForApp(app string) string {
	return firstNonEmpty(config.USDTBEP20Addresses[appcode.Normalize(app)], config.USDTBEP20Address)
}

func normalizeRuntimeRechargeAddressMap(values map[string]string) map[string]string {
	if len(values) == 0 {
		return nil
	}
	normalized := make(map[string]string, len(values))
	for app, address := range values {
		app = appcode.Normalize(app)
		address = strings.TrimSpace(address)
		if app == "" || address == "" {
			continue
		}
		normalized[app] = address
	}
	if len(normalized) == 0 {
		return nil
	}
	return normalized
}
