<?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 App\Framework\Http\Session\Session;

#[MiddlewarePriorityAttribute(MiddlewarePriority::SECURITY, -150)] // Push after Session Creation
final readonly class CsrfMiddleware implements HttpMiddleware
{
    public function __construct(
        private Session $session,
    ){}

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

        if (!$this->session->isStarted()) {
            throw new \RuntimeException('Session must be started before CSRF validation');
        }

        if($request->method === Method::POST) {
            // FormId ist jetzt immer vorhanden durch automatische Generierung
            $formId = $request->parsedBody->get('_form_id');
            $token = $request->parsedBody->get('_token');

            if (!$formId || !$token) {
                throw new \Exception('CSRF-Daten fehlen');
            }

            $valid = $this->session->csrf->validateToken($formId, $token);

            if(!$valid) {
                throw new \Exception('CSRF-Token ungültig');
            }
        }

        return $next($context);
    }
}
