<?php
/**
 * REST API Guard
 *
 * Rate-limits REST API requests per IP and optionally restricts
 * guest access to the /wp/v2/users endpoint.
 *
 * @package GuardianShield
 */

namespace GuardianShield;

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

class RestApiGuard {

	private Logger      $logger;
	private RateLimiter $rate_limiter;

	public function __construct( Logger $logger, RateLimiter $rate_limiter ) {
		$this->logger       = $logger;
		$this->rate_limiter = $rate_limiter;
	}

	public function register_hooks(): void {
		add_filter( 'rest_authentication_errors', [ $this, 'check_rest_auth' ] );
		add_action( 'rest_api_init', [ $this, 'rate_limit_rest' ], 1 );
	}

	/** Log REST access; return $result unchanged (hook chain compatible). */
	public function check_rest_auth( $result ) {
		if ( ! empty( $result ) ) {
			return $result;
		}

		$ip = gs_get_client_ip();
		$this->logger->log_firewall_event( [
			'ip_address'   => $ip,
			'rule_matched' => 'rest_api_access',
			'action'       => 'log',
			'request_uri'  => $_SERVER['REQUEST_URI'] ?? '',
		] );

		return $result;
	}

	public function rate_limit_rest(): void {
		$ip = gs_get_client_ip();
		if ( ! $this->rate_limiter->check_and_record( $ip, 'rest' ) ) {
			wp_send_json_error(
				[ 'message' => 'Too many requests. Please slow down.' ],
				429
			);
		}
	}
}
