package gateway

import (
	"context"
	"fmt"

	"go.uber.org/zap"

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

// CheckPasswordBreachUseCase checks if a password has been compromised in data breaches
// CWE-521: Password breach checking to prevent use of compromised passwords
type CheckPasswordBreachUseCase struct {
	breachChecker password.BreachChecker
	logger        *zap.Logger
}

// ProvideCheckPasswordBreachUseCase creates a new CheckPasswordBreachUseCase
func ProvideCheckPasswordBreachUseCase(
	breachChecker password.BreachChecker,
	logger *zap.Logger,
) *CheckPasswordBreachUseCase {
	return &CheckPasswordBreachUseCase{
		breachChecker: breachChecker,
		logger:        logger.Named("check-password-breach-usecase"),
	}
}

// Execute checks if a password has been found in known data breaches
// Returns an error if the password has been breached
func (uc *CheckPasswordBreachUseCase) Execute(ctx context.Context, passwordStr string) error {
	uc.logger.Debug("checking password against breach database")

	breachCount, err := uc.breachChecker.CheckPassword(ctx, passwordStr)
	if err != nil {
		// Log error but don't fail registration/login if breach check fails
		// This is a defense-in-depth measure, not a critical security control
		uc.logger.Warn("failed to check password breach status (non-fatal)",
			zap.Error(err))
		return nil // Don't block user if service is down
	}

	if breachCount > 0 {
		uc.logger.Warn("password found in data breaches",
			zap.Int("breach_count", breachCount))
		return fmt.Errorf("password has been found in %d data breaches and cannot be used", breachCount)
	}

	uc.logger.Debug("password not found in breaches")
	return nil
}
