// Package router ...
//
// Description : router ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-02-07 17:36
package router

import (
	"errors"
	"fmt"
	"reflect"
	"strings"

	"github.com/go-playground/validator/v10"
)

var defaultValidateErrTag = "err"

// SetValidateErrTag 设置验证失败时, 获取错误信息的tag字段
func SetValidateErrTag(tagName string) {
	tagName = strings.TrimSpace(tagName)
	if tagName == "" {
		return
	}
	defaultValidateErrTag = tagName
}

// GetValidateErr 格式化错误信息
func GetValidateErr(obj any, rawErr error) error {
	if nil == rawErr {
		return nil
	}
	if nil == obj {
		return rawErr
	}
	var (
		ok             bool
		validationErrs validator.ValidationErrors
		errString      []string
		field          reflect.StructField
	)
	if ok = errors.As(rawErr, &validationErrs); !ok {
		return rawErr
	}
	objType := reflect.TypeOf(obj)
	if objType.Kind() == reflect.Ptr {
		objType = objType.Elem()
	}
	for _, validationErr := range validationErrs {
		if field, ok = objType.FieldByName(validationErr.Field()); ok {
			if e := field.Tag.Get(defaultValidateErrTag); e != "" {
				errString = append(errString, fmt.Sprintf("%s: %s", field.Tag.Get("json"), e))
				continue
			} else {
				errString = append(errString, fmt.Sprintf("%s: %v", field.Tag.Get("json"), validationErr.Value()))
			}
		}
		errString = append(errString, validationErr.Error())
	}
	return errors.New(strings.Join(errString, "\n"))
}
