package gateway

import (
	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/security/password"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/security/securestring"
)

// HashPasswordUseCase handles password validation and hashing
type HashPasswordUseCase struct {
	passwordProvider  password.PasswordProvider
	passwordValidator password.PasswordValidator
	logger            *zap.Logger
}

// ProvideHashPasswordUseCase creates a new HashPasswordUseCase
func ProvideHashPasswordUseCase(
	passwordProvider password.PasswordProvider,
	passwordValidator password.PasswordValidator,
	logger *zap.Logger,
) *HashPasswordUseCase {
	return &HashPasswordUseCase{
		passwordProvider:  passwordProvider,
		passwordValidator: passwordValidator,
		logger:            logger.Named("hash-password-usecase"),
	}
}

// Execute validates password strength and returns the hashed password
func (uc *HashPasswordUseCase) Execute(plainPassword string) (string, error) {
	// Validate password strength
	if err := uc.passwordValidator.ValidatePasswordStrength(plainPassword); err != nil {
		uc.logger.Warn("password validation failed", zap.Error(err))
		return "", err
	}

	// Hash the password using secure string
	securePassword, err := securestring.NewSecureString(plainPassword)
	if err != nil {
		uc.logger.Error("failed to create secure string", zap.Error(err))
		return "", err
	}
	defer securePassword.Wipe() // Clean up password from memory

	passwordHash, err := uc.passwordProvider.GenerateHashFromPassword(securePassword)
	if err != nil {
		uc.logger.Error("failed to hash password", zap.Error(err))
		return "", err
	}

	uc.logger.Debug("password hashed successfully")
	return passwordHash, nil
}
