package auth

import (
	"regexp"
	"strings"

	apperrors "github.com/nexuscrm/kernel/pkg/errors"
	"github.com/nexuscrm/kernel/pkg/passwordhash"
)

// HashPassword hashes a password using bcrypt
func HashPassword(password string) (string, error) {
	return passwordhash.Hash(password)
}

// VerifyPassword compares a plain password with a hashed password
func VerifyPassword(password, hash string) bool {
	return passwordhash.Verify(password, hash)
}

// ValidateBcryptCost checks that a bcrypt hash meets the minimum cost factor.
// Returns an error if the cost is below bcrypt.DefaultCost.
func ValidateBcryptCost(hash string) error {
	return passwordhash.ValidateCost(hash)
}

// ValidatePasswordStrength checks if a password meets security requirements
func ValidatePasswordStrength(password string) error {
	if len(password) < 8 {
		return apperrors.NewValidationError("password", "must be at least 8 characters long")
	}

	if len(password) > 128 {
		return apperrors.NewValidationError("password", "must not exceed 128 characters")
	}

	// Check for at least one uppercase letter
	if !regexp.MustCompile(`[A-Z]`).MatchString(password) {
		return apperrors.NewValidationError("password", "must contain at least one uppercase letter")
	}

	// Check for at least one lowercase letter
	if !regexp.MustCompile(`[a-z]`).MatchString(password) {
		return apperrors.NewValidationError("password", "must contain at least one lowercase letter")
	}

	// Check for at least one digit
	if !regexp.MustCompile(`[0-9]`).MatchString(password) {
		return apperrors.NewValidationError("password", "must contain at least one number")
	}

	// Check for at least one special character
	if !regexp.MustCompile(`[@$!%*?&]`).MatchString(password) {
		return apperrors.NewValidationError("password", "must contain at least one special character (@$!%*?&)")
	}

	return nil
}

// IsValidEmail validates an email address format
func IsValidEmail(email string) bool {
	email = strings.TrimSpace(email)
	if len(email) < 3 || len(email) > 254 {
		return false
	}

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