package validator

import (
	"errors"
	"regexp"
	"strings"

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

func isValidEmail(email string) bool {
	emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	return emailRegex.MatchString(email)
}

func isValidPhone(phone string) bool {
	phoneRegex := regexp.MustCompile(`^\+?[1-9]\d{1,14}$`)
	return phoneRegex.MatchString(phone)
}

func isValidRole(role string) bool {
	validRoles := map[string]bool{
		"admin":   true,
		"manager": true,
		"cashier": true,
	}
	return validRoles[role]
}

func isValidPlanType(planType string) bool {
	validPlanTypes := map[string]bool{
		"basic":      true,
		"premium":    true,
		"enterprise": true,
	}
	return validPlanTypes[planType]
}

func formatValidationError(err error) error {
	if validationErrors, ok := err.(validator.ValidationErrors); ok {
		var errorMessages []string
		for _, fieldError := range validationErrors {
			switch fieldError.Tag() {
			case "required":
				errorMessages = append(errorMessages, fieldError.Field()+" is required")
			case "email":
				errorMessages = append(errorMessages, fieldError.Field()+" must be a valid email")
			case "min":
				errorMessages = append(errorMessages, fieldError.Field()+" must be at least "+fieldError.Param())
			case "max":
				errorMessages = append(errorMessages, fieldError.Field()+" must be at most "+fieldError.Param())
			case "oneof":
				errorMessages = append(errorMessages, fieldError.Field()+" must be one of: "+fieldError.Param())
			default:
				errorMessages = append(errorMessages, fieldError.Field()+" is invalid")
			}
		}
		return errors.New(strings.Join(errorMessages, "; "))
	}
	return err
}
