<?php

declare(strict_types=1);

namespace App\Framework\Http\Middlewares;

use App\Framework\Exception\Security\HoneypotTriggeredException;
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\Next;
use App\Framework\Http\Request;
use App\Framework\Http\RequestStateManager;
use App\Framework\Logging\Logger;

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

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

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

        return $next($context);
    }

    private function validateHoneypot(Request $request): void
    {
        // Skip honeypot validation for API routes and LiveComponent AJAX endpoints
        if (str_starts_with($request->path, '/api/') ||
            str_starts_with($request->path, '/live-component/') ||
            str_starts_with($request->path, '/livecomponent/')) {
            return;
        }

        $honeypotName = $request->parsedBody->get('_honeypot_name');

        if (! $honeypotName) {
            $this->logSuspiciousActivity('Missing honeypot name', $request);

            throw HoneypotTriggeredException::missingHoneypotName();
        }

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

        // Honeypot wurde ausgefüllt = Bot erkannt
        if (! empty($honeypotValue)) {
            $this->logSuspiciousActivity("Honeypot filled: {$honeypotName} = {$honeypotValue}", $request);

            throw HoneypotTriggeredException::honeypotFilled($honeypotName, $honeypotValue);
        }

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

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

        if ($startTime) {
            $elapsedSeconds = time() - (int)$startTime;
            $minimumSeconds = 2;

            if ($elapsedSeconds < $minimumSeconds) {
                $this->logSuspiciousActivity('Form submitted too quickly', $request);

                throw HoneypotTriggeredException::submittedTooQuickly($elapsedSeconds, $minimumSeconds);
            }
        }
    }

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