<?php
/**
 * Validates the root Schema.org context.
 *
 * @package SEOvaultSEO\Schema\Validation\Rules\Core
 */

namespace SEOvaultSEO\Schema\Validation\Rules\Core;

use SEOvaultSEO\Schema\Validation\RuleInterface;
use SEOvaultSEO\Schema\Validation\Severity;
use SEOvaultSEO\Schema\Validation\ValidationContext;
use SEOvaultSEO\Schema\Validation\ValidationIssue;

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

/**
 * Requires one supported root JSON-LD context.
 */
class ContextRule implements RuleInterface {

	/**
	 * Get the stable rule code.
	 *
	 * @return string
	 */
	public function get_code() {
		return 'schema.context';
	}

	/**
	 * Context applies to every local schema graph.
	 *
	 * @param ValidationContext $context Validation context.
	 * @return bool
	 */
	public function supports( ValidationContext $context ) {
		return true;
	}

	/**
	 * Validate the root context.
	 *
	 * @param ValidationContext $context Validation context.
	 * @return ValidationIssue[]
	 */
	public function evaluate( ValidationContext $context ) {
		$graph   = $context->get_graph();
		$value   = $graph['@context'] ?? null;
		$source  = $context->get_source();
		$issues  = array();
		$allowed = array( 'https://schema.org', 'https://schema.org/' );

		if ( null === $value || '' === $value ) {
			$issues[] = new ValidationIssue(
				array(
					'code'        => 'schema.context.missing',
					'severity'    => Severity::ERROR,
					'category'    => 'core',
					'path'        => '@context',
					'source'      => $source,
					'title_key'   => 'schema.context_missing.title',
					'message_key' => 'schema.context_missing.message',
				)
			);
			return $issues;
		}

		if ( ! is_string( $value ) || ! in_array( $value, $allowed, true ) ) {
			$issues[] = new ValidationIssue(
				array(
					'code'        => 'schema.context.unsupported',
					'severity'    => Severity::WARNING,
					'category'    => 'core',
					'path'        => '@context',
					'source'      => $source,
					'title_key'   => 'schema.context_unsupported.title',
					'message_key' => 'schema.context_unsupported.message',
				)
			);
		}

		return $issues;
	}
}
