<?php

namespace Waypoint\Agent\Compat;

use Waypoint\Agent\Base\Thing;

class Wpo_Bypass extends Thing {

	public function attach_hooks(): void {
		if ( self::is_agent_rest_request() && ! defined( 'WPO_AUTH_SCENARIO' ) ) {
			define( 'WPO_AUTH_SCENARIO', 'internet' );
		}

		add_action( 'plugins_loaded', [ $this, 'maybe_skip_wpo_auth' ], 1 );
	}

	public function maybe_skip_wpo_auth(): void {
		if ( ! self::is_agent_rest_request() ) {
			return;
		}
		add_filter( 'wpo365_skip_authentication', '__return_true', PHP_INT_MAX );
	}

	public static function is_agent_rest_request(): bool {
		$uri = isset( $_SERVER['REQUEST_URI'] ) ? (string) $_SERVER['REQUEST_URI'] : '';
		if ( '' === $uri ) {
			return false;
		}
		$pattern = sprintf(
			'#/wp-json/(%s|%s)/\S+#',
			preg_quote( WAYPOINT_MONITOR_REST_NS, '#' ),
			preg_quote( WAYPOINT_MONITOR_AGENT_REST_NS, '#' )
		);
		return (bool) preg_match( $pattern, $uri );
	}
}
