<?php
/**
 * Query constraints finalizer.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Frontend\Engine\Filters\Query;

defined( 'ABSPATH' ) || exit;

/**
 * Query constraints finalizer.
 */
class ConstraintsFinalizer {

	/**
	 * Normalize include IDs and apply preferred IDs ordering constraints.
	 *
	 * @param int[]|null $include_ids Include IDs constraint.
	 * @param array      $context Context.
	 * @return array{include_ids: int[]|null, enforce_empty: bool}
	 */
	public function finalize( $include_ids, $context ) {
		$enforce_empty = false;

		if ( is_array( $include_ids ) ) {
			$include_ids = array_values( array_unique( array_filter( array_map( 'absint', $include_ids ) ) ) );
			if ( empty( $include_ids ) ) {
				$enforce_empty = true;
			}
		}

		if ( ! $enforce_empty && isset( $context['_preferred_ids'] ) && is_array( $context['_preferred_ids'] ) ) {
			$preferred = array_values( array_unique( array_filter( array_map( 'absint', $context['_preferred_ids'] ) ) ) );
			if ( empty( $preferred ) ) {
				$enforce_empty = true;
			} else {
				if ( is_array( $include_ids ) ) {
					$preferred = array_values( array_intersect( $preferred, $include_ids ) );
					if ( empty( $preferred ) ) {
						$enforce_empty = true;
					}
				}

				if ( ! $enforce_empty ) {
					$include_ids = $preferred;
				}
			}
		}

		return array(
			'include_ids'   => $include_ids,
			'enforce_empty' => $enforce_empty,
		);
	}
}
