<?php

namespace EasyLinkAutomations\HTTP\Middleware;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Config;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

/**
 * Verifies the WordPress AJAX nonce on every protected request.
 */
final class NonceCheckerMiddleware
{
    public function handle(Request $request): Response|bool
    {
        $nonce = sanitize_text_field(wp_unslash((string) $request->get('_ajax_nonce', '')));

        if (
            !$request->has('_ajax_nonce')
            || !wp_verify_nonce($nonce, Config::withPrefix('nonce'))
        ) {
            return Response::error('Invalid nonce token')->httpStatus(403);
        }

        return true;
    }
}
