<?php

declare(strict_types=1);

namespace App\Framework\Exception\Security;

use App\Framework\Exception\ErrorCode;
use App\Framework\Exception\ExceptionContext;
use App\Framework\Exception\SecurityException;
use App\Framework\Security\Events\BotDetectedEvent;

/**
 * Exception for honeypot spam protection triggers
 */
final class HoneypotTriggeredException extends SecurityException
{
    public static function missingHoneypotName(): self
    {
        $event = new BotDetectedEvent(
            reason: 'Missing honeypot field in form submission',
            ip: $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            userAgent: $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        );

        $context = ExceptionContext::forOperation('security.honeypot', 'HoneypotMiddleware')
            ->withData([
                'validation_type' => 'missing_honeypot_name',
                'risk_level' => 'high',
            ]);

        return new self(
            securityEvent: $event,
            message: 'Spam protection triggered: Missing honeypot field',
            additionalContext: $context
        );
    }

    public static function honeypotFilled(string $fieldName, string $value): self
    {
        $event = new BotDetectedEvent(
            reason: "Honeypot field '{$fieldName}' was filled",
            ip: $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            userAgent: $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        );

        $context = ExceptionContext::forOperation('security.honeypot', 'HoneypotMiddleware')
            ->withData([
                'validation_type' => 'honeypot_filled',
                'field_name' => $fieldName,
                'field_value_length' => strlen($value),
                'risk_level' => 'high',
            ])
            ->withDebug([
                'field_value' => substr($value, 0, 100), // Limit für Logging
            ]);

        return new self(
            securityEvent: $event,
            message: 'Spam protection triggered: Honeypot field was filled',
            additionalContext: $context
        );
    }

    public static function submittedTooQuickly(int $elapsedSeconds, int $minimumSeconds = 2): self
    {
        $event = new BotDetectedEvent(
            reason: "Form submitted too quickly ({$elapsedSeconds}s < {$minimumSeconds}s)",
            ip: $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            userAgent: $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        );

        $context = ExceptionContext::forOperation('security.honeypot', 'HoneypotMiddleware')
            ->withData([
                'validation_type' => 'submission_too_fast',
                'elapsed_seconds' => $elapsedSeconds,
                'minimum_seconds' => $minimumSeconds,
                'risk_level' => 'medium',
            ]);

        return new self(
            securityEvent: $event,
            message: 'Spam protection triggered: Form submitted too quickly',
            additionalContext: $context
        );
    }
}
