package domain

import (
	"fmt"
	"regexp"
	"strings"
	"unicode/utf8"
)

// Validation errors
var (
	ErrEmptyField       = fmt.Errorf("field cannot be empty")
	ErrInvalidEmail     = fmt.Errorf("invalid email format")
	ErrInvalidPhone     = fmt.Errorf("invalid phone format")
	ErrPasswordTooShort = fmt.Errorf("password is too short")
	ErrPasswordTooLong  = fmt.Errorf("password is too long")
	ErrInvalidLength    = fmt.Errorf("invalid field length")
)

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

// Phone validation regex (supports international formats)
var phoneRegex = regexp.MustCompile(`^\+?[1-9]\d{2,14}$`)

// ValidateEmail validates an email address format
func ValidateEmail(email string) error {
	if email == "" {
		return ErrEmptyField
	}

	email = strings.TrimSpace(email)
	if !emailRegex.MatchString(email) {
		return ErrInvalidEmail
	}

	return nil
}

// ValidatePhone validates a phone number format
func ValidatePhone(phone string) error {
	if phone == "" {
		return ErrEmptyField
	}

	phone = strings.TrimSpace(phone)
	if !phoneRegex.MatchString(phone) {
		return ErrInvalidPhone
	}

	return nil
}

// ValidatePassword validates password strength
func ValidatePassword(password string) error {
	if password == "" {
		return ErrEmptyField
	}

	length := utf8.RuneCountInString(password)
	if length < MinPasswordLength {
		return ErrPasswordTooShort
	}

	if length > MaxPasswordLength {
		return ErrPasswordTooLong
	}

	return nil
}

// ValidateStringLength validates string length within specified bounds
func ValidateStringLength(field, value string, min, max int) error {
	if value == "" {
		return ErrEmptyField
	}

	length := utf8.RuneCountInString(value)
	if length < min || length > max {
		return ErrInvalidLength
	}

	return nil
}

// ValidateRequired validates that a required field is not empty
func ValidateRequired(field, value string) error {
	if strings.TrimSpace(value) == "" {
		return ErrEmptyField
	}

	return nil
}
