<?php
/**
 * Dismissed Suggestions store.
 *
 * Remembers suggestion pairs (source post → target post) the user has
 * explicitly dismissed, so they are never surfaced again — in either the
 * editor panel or bulk mode. Complements LinkMemory (which records links that
 * were *built*); this records links the user decided they *don't* want.
 *
 * Stored as post meta on the source post: an array of dismissed target IDs.
 *
 * @package Platform\Helm\Modules\Link_Suggester
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Link_Suggester;

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

final class DismissedSuggestions {

	private const META_KEY = '_platform_helm_dismissed_links';

	public function dismiss( int $source_id, int $target_id ): void {
		if ( $source_id <= 0 || $target_id <= 0 ) {
			return;
		}
		$list = $this->for_source( $source_id );
		if ( in_array( $target_id, $list, true ) ) {
			return;
		}
		$list[] = $target_id;
		update_post_meta( $source_id, self::META_KEY, array_values( array_unique( $list ) ) );
	}

	public function is_dismissed( int $source_id, int $target_id ): bool {
		if ( $source_id <= 0 || $target_id <= 0 ) {
			return false;
		}
		return in_array( $target_id, $this->for_source( $source_id ), true );
	}

	/**
	 * @return int[]
	 */
	public function for_source( int $source_id ): array {
		$stored = get_post_meta( $source_id, self::META_KEY, true );
		if ( ! is_array( $stored ) ) {
			return [];
		}
		return array_values( array_filter( array_map( 'intval', $stored ) ) );
	}

	public function restore( int $source_id, int $target_id ): void {
		$list = $this->for_source( $source_id );
		$list = array_values( array_filter( $list, static fn( $id ) => $id !== $target_id ) );
		if ( empty( $list ) ) {
			delete_post_meta( $source_id, self::META_KEY );
		} else {
			update_post_meta( $source_id, self::META_KEY, $list );
		}
	}
}
