package validator

import (
	"context"
	"fmt"
	"unicode/utf8"

	"entgo.io/ent"
	"gitlab.galaxy-immi.com/Backend-group/go-com/consts/codes/errcode"
)

func MaxRuneLen(fieldName string, maxlen int) ent.Hook {
	return func(next ent.Mutator) ent.Mutator {
		return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
			if value, exists := m.Field(fieldName); exists {
				if str, ok := value.(string); ok {
					if utf8.RuneCountInString(str) > maxlen {
						enErrMsg := fmt.Sprintf("%s exceeds the maximum length of %d", fieldName, maxlen)
						zhErrMsg := fmt.Sprintf("%s不允许超过%d个字符", fieldName, maxlen)
						return nil, errcode.ErrInvalidArgument.
							WithEnDesc(enErrMsg).
							WithDesc(zhErrMsg)
					}
				}
			}
			return next.Mutate(ctx, m)
		})
	}
}
