<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Cockpit;

defined( 'ABSPATH' ) || exit;

/**
 * REST-Permission-Callback fuer die Server-zu-Server-Routen (/verify,
 * /agents/sync). Baut die Header/Body-Werte aus dem WP_REST_Request und
 * delegiert an SignatureVerifier mit dem site_key aus der Config.
 */
class SignatureGuard {

	private Config $config;

	private SignatureVerifier $verifier;

	/**
	 * @param Config            $config   Kopplungs-Zustand.
	 * @param SignatureVerifier $verifier Signaturpruefung.
	 */
	public function __construct( Config $config, SignatureVerifier $verifier ) {
		$this->config   = $config;
		$this->verifier = $verifier;
	}

	/**
	 * Prueft die Server-Signatur eines Requests.
	 *
	 * @param \WP_REST_Request $request Request.
	 * @return true|\WP_Error
	 */
	public function permission( \WP_REST_Request $request ) {
		return $this->verifier->verify(
			(string) $request->get_method(),
			(string) $request->get_route(),
			(string) $request->get_body(),
			array(
				'timestamp'   => (string) $request->get_header( 'X-Kurato-Timestamp' ),
				'nonce'       => (string) $request->get_header( 'X-Kurato-Nonce' ),
				'key_version' => (string) $request->get_header( 'X-Kurato-Key-Version' ),
				'signature'   => (string) $request->get_header( 'X-Kurato-Signature' ),
			),
			$this->config->site_key(),
			$this->config->key_version()
		);
	}
}
