<?php
/**
 * Detects duplicate entity identifiers.
 *
 * @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;
}

/**
 * Reports every entity that reuses an earlier non-empty @id.
 */
class DuplicateIdRule implements RuleInterface {

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

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

	/**
	 * Detect duplicate entity IDs.
	 *
	 * @param ValidationContext $context Validation context.
	 * @return ValidationIssue[]
	 */
	public function evaluate( ValidationContext $context ) {
		$seen   = array();
		$issues = array();

		foreach ( $context->get_entities() as $entity ) {
			$id = $entity['id'] ?? '';
			if ( ! is_string( $id ) || '' === $id ) {
				continue;
			}
			if ( ! isset( $seen[ $id ] ) ) {
				$seen[ $id ] = true;
				continue;
			}

			$issues[] = new ValidationIssue(
				array(
					'code'        => 'graph.id.duplicate',
					'severity'    => Severity::ERROR,
					'category'    => 'core',
					'entity_type' => implode( ', ', $entity['types'] ?? array() ),
					'entity_id'   => $id,
					'path'        => ( $entity['path'] ?? '' ) . '.@id',
					'source'      => $context->get_source(),
					'title_key'   => 'graph.id_duplicate.title',
					'message_key' => 'graph.id_duplicate.message',
				)
			);
		}

		return $issues;
	}
}
