<?php
/**
 * RequestValidator class.
 *
 * Validates the origin of REST API requests to ensure they come from the allowed host.
 *
 * @package Ilabs\Firevert\Core\Api\Validator
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Api\Validator;

use WP_REST_Request;
use WP_Error;

/**
 * Class RequestValidator.
 */
final class RequestValidator {

	/**
	 * Validates the request origin.
	 *
	 * Ensures that incoming REST API requests originate from the same domain
	 * as the WordPress site, based on the 'origin' or 'referer' headers.
	 *
	 * @param WP_REST_Request $request The incoming REST request.
	 *
	 * @return true|WP_Error True if the request is valid, or WP_Error if invalid.
	 */
	public function validate_request_origin( WP_REST_Request $request ) {
		$origin  = $request->get_header( 'origin' );
		$referer = $request->get_header( 'referer' );

		$allowed_host = wp_parse_url( get_site_url(), PHP_URL_HOST );

		$origin_host  = wp_parse_url( $origin, PHP_URL_HOST );
		$referer_host = wp_parse_url( $referer, PHP_URL_HOST );

		if ( $origin_host !== $allowed_host && $referer_host !== $allowed_host ) {
			return new WP_Error(
				'firevert_invalid_origin',
				'Access denied: invalid origin.',
				array(
					'status' => 403,
				)
			);
		}

		return true;
	}
}
