package validators

import (
	"errors"
	"net/mail"
	"regexp"
	"strings"
)

var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)

// ValidateEmail checks that an email is non-empty, within length limits,
// and conforms to both RFC 5322 (via net/mail) and a basic regex shape.
func ValidateEmail(email string) error {
	email = strings.TrimSpace(email)
	if email == "" {
		return errors.New("email is required")
	}
	if len(email) > 254 {
		return errors.New("email exceeds maximum length of 254 characters")
	}
	if _, err := mail.ParseAddress(email); err != nil {
		return errors.New("invalid email format")
	}
	if !emailRegex.MatchString(email) {
		return errors.New("invalid email format")
	}
	return nil
}

// NormalizeGiftCardCode strips non-alphanumeric characters and upper-cases the code.
func NormalizeGiftCardCode(code string) string {
	var clean strings.Builder
	for _, char := range code {
		if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') {
			clean.WriteString(string(char))
		}
	}
	return clean.String()
}
