<?php
/**
 * Compact Schema Health cache helpers (local + live post meta).
 *
 * @package SEOvaultSEO\Schema\Validation
 */

namespace SEOvaultSEO\Schema\Validation;

use SEOvaultSEO\Core\Options;
use SEOvaultSEO\Core\PostMeta;

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

/**
 * Deletes and sitewide-generates validation cache without scanning all posts.
 */
class SchemaValidationCache {

	/**
	 * Option key (via Options::get/set) for sitewide lazy invalidation.
	 */
	const GENERATION_OPTION = 'schema_validation_generation';

	/**
	 * Local validation post-meta keys (without PostMeta::PREFIX).
	 *
	 * @var string[]
	 */
	const LOCAL_META_KEYS = array(
		'schema_validation_result',
		'schema_validation_hash',
		'schema_validation_ruleset',
		'schema_validation_time',
	);

	/**
	 * Live validation post-meta keys (without PostMeta::PREFIX).
	 *
	 * @var string[]
	 */
	const LIVE_META_KEYS = array(
		'schema_live_result',
		'schema_live_hash',
		'schema_live_time',
	);

	/**
	 * Full meta keys (with prefix) that invalidation must ignore when written.
	 *
	 * @return string[]
	 */
	public static function ignored_meta_keys() {
		$keys = array();
		foreach ( array_merge( self::LOCAL_META_KEYS, self::LIVE_META_KEYS ) as $key ) {
			$keys[] = PostMeta::PREFIX . $key;
		}
		return $keys;
	}

	/**
	 * Current sitewide validation generation counter.
	 *
	 * @return int
	 */
	public static function get_generation() {
		return max( 0, (int) Options::get( self::GENERATION_OPTION, 0 ) );
	}

	/**
	 * Bump the sitewide generation so every post's next read misses cache.
	 *
	 * @return int New generation value.
	 */
	public static function bump_generation() {
		$next = self::get_generation() + 1;
		Options::set( self::GENERATION_OPTION, $next, false );
		return $next;
	}

	/**
	 * Remove local Schema Health cache for one post.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public static function delete_local( $post_id ) {
		$post_id = (int) $post_id;
		if ( $post_id <= 0 ) {
			return;
		}
		foreach ( self::LOCAL_META_KEYS as $key ) {
			PostMeta::delete( $post_id, $key );
		}
	}

	/**
	 * Remove published-page Schema Health cache for one post.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public static function delete_live( $post_id ) {
		$post_id = (int) $post_id;
		if ( $post_id <= 0 ) {
			return;
		}
		foreach ( self::LIVE_META_KEYS as $key ) {
			PostMeta::delete( $post_id, $key );
		}
	}

	/**
	 * Remove local and live Schema Health cache for one post.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public static function delete_all_for_post( $post_id ) {
		self::delete_local( $post_id );
		self::delete_live( $post_id );
	}
}
