package paymentconfig

// validateCreateRequest 验证创建请求
func (r *Repository) validateCreateRequest(req CreateRequest) error {
	if req.Name == "" {
		return ErrNameRequired
	}
	if req.Provider == "" {
		return ErrInvalidProvider
	}
	if !isValidProvider(req.Provider) {
		return ErrInvalidProvider
	}
	if req.MerchantID == "" {
		return ErrMerchantIDRequired
	}
	if req.SignType != "" && !isValidSignType(req.SignType) {
		return ErrInvalidSignType
	}
	if req.PayWay != "" && !isValidPayWay(req.PayWay) {
		return ErrInvalidPayWay
	}
	if req.Status != "" && !isValidStatus(req.Status) {
		return ErrInvalidStatus
	}

	// leshua 特定验证
	if req.Provider == "leshua" {
		if req.GatewayURL == "" {
			return ErrGatewayURLRequired
		}
		if req.SignKey == "" {
			return ErrSignKeyRequired
		}
		if req.NotifyKey == "" {
			return ErrNotifyKeyRequired
		}
		if req.NotifyURL == "" {
			return ErrNotifyURLRequired
		}
	}
	if req.Provider == "lakala" {
		if req.GatewayURL == "" {
			return ErrGatewayURLRequired
		}
		if req.SignKey == "" {
			return ErrSignKeyRequired
		}
		if req.NotifyKey == "" {
			return ErrNotifyKeyRequired
		}
		if req.NotifyURL == "" {
			return ErrNotifyURLRequired
		}
		if extraString(req.ExtraConfig, "app_id") == "" {
			return ErrAppIDRequired
		}
		if extraString(req.ExtraConfig, "serial_no") == "" {
			return ErrSerialNoRequired
		}
		if extraString(req.ExtraConfig, "term_no") == "" {
			return ErrTermNoRequired
		}
	}

	return nil
}

func isValidProvider(value string) bool {
	return value == "leshua" || value == "lakala" || value == "mock"
}

func isValidSignType(value string) bool {
	return value == "MD5" || value == "SHA256withRSA"
}

// isValidPayWay 校验支付方式是否属于系统支持的微信或支付宝编码。
func isValidPayWay(value string) bool {
	return value == "ZFBZF" || value == "WXZF"
}

func isValidStatus(value string) bool {
	return value == "active" || value == "disabled" || value == "testing"
}

func extraString(config map[string]any, key string) string {
	if config == nil {
		return ""
	}
	value, ok := config[key]
	if !ok || value == nil {
		return ""
	}
	if s, ok := value.(string); ok {
		return s
	}
	return ""
}
