package errors

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

// FromValidatorError convertit une erreur de validation en AppError
func FromValidatorError(err error) *AppError {
	if validationErrors, ok := err.(validator.ValidationErrors); ok {
		details := make([]ErrorDetail, 0, len(validationErrors))

		for _, fieldError := range validationErrors {
			details = append(details, ErrorDetail{
				Field:   fieldError.Field(),
				Message: getValidationMessage(fieldError),
			})
		}

		return &AppError{
			Code:    ErrCodeValidation,
			Message: "Validation failed",
			Details: details,
		}
	}

	return New(ErrCodeValidation, err.Error())
}

// getValidationMessage génère un message d'erreur lisible à partir d'une FieldError
func getValidationMessage(fieldError validator.FieldError) string {
	switch fieldError.Tag() {
	case "required":
		return fieldError.Field() + " is required"
	case "email":
		return fieldError.Field() + " must be a valid email"
	case "min":
		return fieldError.Field() + " must be at least " + fieldError.Param()
	case "max":
		return fieldError.Field() + " must be at most " + fieldError.Param()
	case "len":
		return fieldError.Field() + " must be exactly " + fieldError.Param() + " characters"
	case "gte":
		return fieldError.Field() + " must be greater than or equal to " + fieldError.Param()
	case "lte":
		return fieldError.Field() + " must be less than or equal to " + fieldError.Param()
	case "gt":
		return fieldError.Field() + " must be greater than " + fieldError.Param()
	case "lt":
		return fieldError.Field() + " must be less than " + fieldError.Param()
	case "url":
		return fieldError.Field() + " must be a valid URL"
	case "alphanum":
		return fieldError.Field() + " must contain only alphanumeric characters"
	case "alpha":
		return fieldError.Field() + " must contain only alphabetic characters"
	case "numeric":
		return fieldError.Field() + " must be numeric"
	case "oneof":
		return fieldError.Field() + " must be one of: " + fieldError.Param()
	default:
		return fieldError.Field() + " is invalid"
	}
}
