package paymentutil

import (
	"fmt"
	"strings"
)

func NormalizeStatus(value, fallback string) string {
	switch strings.ToUpper(strings.TrimSpace(value)) {
	case "SUCCESS", "PAID", "TRADE_SUCCESS", "TRADE_FINISHED", "COMPLETED", "PAY_SUCCESS":
		return "success"
	case "WAIT_BUYER_PAY", "USERPAYING", "NOTPAY", "PROCESSING", "PENDING", "CREATED", "ACCEPT", "PAYING":
		return "pending"
	case "CLOSED", "TRADE_CLOSED", "CANCELLED", "CANCELED", "REVOKED", "REFUND", "REFUNDED", "FAILED", "FAIL", "PAYERROR":
		return "failed"
	default:
		return fallback
	}
}

func ConfiguredInt64(values map[string]any, key string, fallback int64) int64 {
	value, ok := values[key]
	if !ok {
		return fallback
	}
	parsed, err := ParseIntegerAmount(strings.TrimSpace(toString(value)))
	if err != nil || parsed <= 0 {
		return fallback
	}
	return parsed
}

func ConfiguredValues(values map[string]any, key string) []string {
	result := []string{}
	for _, item := range strings.Split(toString(values[key]), ",") {
		item = strings.ToUpper(strings.TrimSpace(item))
		if item != "" {
			result = append(result, item)
		}
	}
	return result
}

func ContainsFold(values []string, value string) bool {
	value = strings.ToUpper(strings.TrimSpace(value))
	for _, item := range values {
		if item == value {
			return true
		}
	}
	return false
}

func toString(value any) string {
	if value == nil {
		return ""
	}
	return strings.TrimSpace(strings.ReplaceAll(strings.TrimSpace(stringify(value)), "<nil>", ""))
}

func stringify(value any) string {
	return fmt.Sprint(value)
}
