<?php

declare(strict_types=1);

namespace ServerManager\Middleware;

use ServerManager\Core\Session;
use ServerManager\Core\Security;

class CSRFMiddleware
{
    public function handle(): mixed
    {
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            return null;
        }

        $token = $_POST['_csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';

        $security = new Security();

        if (!$security->validateCSRFToken($token)) {
            if ($this->isApiRequest()) {
                http_response_code(419);
                header('Content-Type: application/json');
                echo json_encode(['error' => 'CSRF token mismatch']);
                exit;
            }

            Session::setFlash('error', 'The form has expired. Please try again.');
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? '/'));
            exit;
        }

        return null;
    }

    private function isApiRequest(): bool
    {
        return str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/api/') ||
               str_starts_with($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json');
    }
}
