<?php

namespace SerpIQ\Api;

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

/**
 * Fail-closed permission for every `serpiq/v1` REST route registered by this plugin.
 *
 * M-11 audit (HTTP entrypoints vs nonce / capability):
 * - Requires capability SERPIQ_CAPABILITY (currently manage_options).
 * - Requires a valid `X-WP-Nonce` header for action `wp_rest` (WordPress REST CSRF).
 * - Does not use $_GET / $_POST / $_REQUEST; callers must not rely on cookie auth alone.
 *
 * Other surfaces (not this class):
 * - Settings POST actions: `check_admin_referer()` + same capability in Admin.
 * - Settings GET UI flags: signed `_wpnonce` (SETTINGS_UI_NONCE_ACTION) before reading.
 * - OAuth “Connect” / “Disconnect” GET: dedicated admin nonces; Google callback uses OAuth `state`.
 * - WP-Cron hooks: no logged-in user; scheduled by WordPress; not browser-addressable.
 * - WP-CLI: no browser nonce; trust model is shell access (see Cli package docblock).
 */
final class Rest_Permission {

	public static function admin_rest_request( \WP_REST_Request $request ): bool {
		if ( ! current_user_can( SERPIQ_CAPABILITY ) ) {
			return false;
		}

		$nonce = (string) $request->get_header( 'X-WP-Nonce' );
		if ( '' === $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
			return false;
		}

		return true;
	}
}
