package paymentutil

import (
	"encoding/json"
	"fmt"
	"strings"
)

func JSONObject(raw []byte) map[string]any {
	var value any
	if json.Unmarshal(raw, &value) != nil {
		return nil
	}
	object, _ := value.(map[string]any)
	return object
}

func NestedString(value any, keys ...string) string {
	found := nestedValue(value, keys...)
	if found == nil {
		return ""
	}
	return strings.TrimSpace(fmt.Sprint(found))
}

func StringAtPath(value any, path string) string {
	found := ValueAtPath(value, path)
	if found == nil {
		return ""
	}
	return strings.TrimSpace(fmt.Sprint(found))
}

func ValueAtPath(value any, path string) any {
	path = strings.TrimSpace(path)
	if path == "" {
		return nil
	}
	current := value
	for _, part := range strings.Split(path, ".") {
		object, ok := current.(map[string]any)
		if !ok {
			return nil
		}
		current = object[part]
	}
	return current
}

func nestedValue(value any, keys ...string) any {
	object, ok := value.(map[string]any)
	if !ok {
		return nil
	}
	for _, key := range keys {
		if found, exists := object[key]; exists && found != nil && fmt.Sprint(found) != "" {
			return found
		}
	}
	for _, nestedKey := range []string{"data", "result", "order", "transaction", "response"} {
		if found := nestedValue(object[nestedKey], keys...); found != nil {
			return found
		}
	}
	return nil
}
