package util

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

// StructToMap 将结构体转换为 map[string]any
func StructToMap(v any) (map[string]any, error) {
	b, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}
	var m map[string]any
	err = json.Unmarshal(b, &m)
	return m, err
}

func StructToMapWithReflect(obj interface{}) map[string]interface{} {
	val := reflect.ValueOf(obj)
	if val.Kind() == reflect.Ptr {
		val = val.Elem()
	}
	if val.Kind() != reflect.Struct {
		return nil
	}

	data := make(map[string]interface{})
	for i := 0; i < val.NumField(); i++ {
		valueField := val.Field(i)
		typeField := val.Type().Field(i)
		jsonTag := typeField.Tag.Get("json")
		if idx := strings.Index(jsonTag, ","); idx != -1 {
			jsonTag = jsonTag[:idx]
		}
		if !typeField.IsExported() {
			continue
		}
		data[jsonTag] = valueField.Interface()
	}
	return data
}
