<?php
/**
 * Detects empty values in top-level entity properties.
 *
 * @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;
use SEOvaultSEO\Schema\Validation\ValueInspector;

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

/**
 * Reports explicitly supplied empty values without treating zero or false as empty.
 */
class EmptyValueRule implements RuleInterface {

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

	/**
	 * Empty-value checks apply to every graph.
	 *
	 * @param ValidationContext $context Validation context.
	 * @return bool
	 */
	public function supports( ValidationContext $context ) {
		return true;
	}

	/**
	 * Report explicit empty values on top-level graph entities.
	 *
	 * @param ValidationContext $context Validation context.
	 * @return ValidationIssue[]
	 */
	public function evaluate( ValidationContext $context ) {
		$issues = array();
		foreach ( $context->get_entities() as $entity ) {
			if ( empty( $entity['is_top_level'] ) ) {
				continue;
			}

			ValueInspector::walk(
				$entity['data'] ?? array(),
				$entity['path'] ?? '',
				function ( $property, $value, $path ) use ( &$issues, $entity, $context ) {
					if ( in_array( $property, array( '@context', '@type', '@id', '@graph' ), true ) || ! ValueInspector::is_empty( $value ) ) {
						return;
					}

					$issues[] = new ValidationIssue(
						array(
							'code'        => 'schema.value.empty',
							'severity'    => Severity::WARNING,
							'category'    => 'core',
							'entity_type' => implode( ', ', $entity['types'] ?? array() ),
							'entity_id'   => $entity['id'] ?? '',
							'path'        => $path,
							'source'      => $context->get_source(),
							'title_key'   => 'schema.value_empty.title',
							'message_key' => 'schema.value_empty.message',
						)
					);
				}
			);
		}

		return $issues;
	}
}
