<?php
declare(strict_types=1);

namespace App\Framework\Http\Middlewares;

use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\Method;
use App\Framework\Http\MiddlewareContext;
use App\Framework\Http\MiddlewarePriority;
use App\Framework\Http\MiddlewarePriorityAttribute;
use App\Framework\Http\RequestStateManager;
use Psr\Log\LoggerInterface;

#[MiddlewarePriorityAttribute(MiddlewarePriority::SECURITY, -140)] // Nach CSRF, vor anderen Validierungen
final readonly class HoneypotMiddleware implements HttpMiddleware
{
    public function __construct(
        private ?LoggerInterface $logger = null
    ) {}

    public function __invoke(MiddlewareContext $context, callable $next, RequestStateManager $stateManager): MiddlewareContext
    {
        $request = $context->request;

        if ($request->method === Method::POST) {
            $this->validateHoneypot($request);
        }

        return $next($context);
    }

    private function validateHoneypot($request): void
    {
        $honeypotName = $request->parsedBody->get('_honeypot_name');

        if (!$honeypotName) {
            $this->logSuspiciousActivity('Missing honeypot name', $request);
            throw new \Exception('Spam-Schutz ausgelöst');
        }

        $honeypotValue = $request->parsedBody->get($honeypotName);

        // Honeypot wurde ausgefüllt = Bot erkannt
        if (!empty($honeypotValue)) {
            $this->logSuspiciousActivity("Honeypot filled: {$honeypotName} = {$honeypotValue}", $request);
            throw new \Exception('Spam-Schutz ausgelöst');
        }

        // Zusätzliche Zeit-basierte Validierung (optional)
        $this->validateSubmissionTime($request);
    }

    private function validateSubmissionTime($request): void
    {
        // Formulare, die zu schnell abgeschickt werden, sind verdächtig
        $startTime = $request->parsedBody->get('_form_start_time');

        if ($startTime && (time() - (int)$startTime) < 2) {
            $this->logSuspiciousActivity('Form submitted too quickly', $request);
            throw new \Exception('Spam-Schutz ausgelöst');
        }
    }

    private function logSuspiciousActivity(string $reason, $request): void
    {
        if ($this->logger) {
            $this->logger->warning('Honeypot triggered', [
                'reason' => $reason,
                'ip' => $request->getClientIp(),
                'user_agent' => $request->headers->get('User-Agent') ?? 'unknown',
                'url' => $request->uri
            ]);
        }
    }
}
