<?php

/**
 * Middleware для захисту від CSRF атак
 *
 * @package Flowaxy\Interface\Http\Middleware
 * @version 1.0.0 Alpha prerelease
 */

declare(strict_types=1);

namespace Flowaxy\Interface\Http\Middleware;

use Flowaxy\Interface\Http\Request;
use Flowaxy\Interface\Http\Response;
use Flowaxy\Infrastructure\Security\Security;

final class CsrfMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next)
    {
        // Проверяем только POST, PUT, DELETE запросы
        $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        if (!in_array($method, ['POST', 'PUT', 'DELETE', 'PATCH'])) {
            return $next($request);
        }

        $token = $request->get('_token') ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? null);
        $sessionToken = $_SESSION['csrf_token'] ?? null;

        if ($token === null || $sessionToken === null || $token !== $sessionToken) {
            return new Response(['error' => 'Invalid CSRF token'], 403);
        }

        return $next($request);
    }
}
