<?php
/**
 * Query context resolver.
 *
 * @package PRECO
 */

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

defined( 'ABSPATH' ) || exit;

/**
 * Query context resolver.
 */
class ContextResolver {

	/**
	 * Resolve the current product, its ID, and exclude IDs from raw context.
	 *
	 * @param array $context Context.
	 * @return array{product_id:int, product: ?\WC_Product, exclude_ids:int[], order_id:int}
	 */
	public function resolve( $context ) {
		$product_id = isset( $context['product_id'] ) ? absint( $context['product_id'] ) : 0;
		$product    = $product_id ? \wc_get_product( $product_id ) : null;
		if ( $product && ! ( $product instanceof \WC_Product ) ) {
			$product = null;
		}

		$exclude_ids = isset( $context['exclude_ids'] ) && is_array( $context['exclude_ids'] )
			? array_map( 'absint', $context['exclude_ids'] )
			: array();
		if ( $product_id ) {
			$exclude_ids[] = $product_id;
		}
		$exclude_ids = array_values( array_unique( array_filter( $exclude_ids ) ) );

		return array(
			'product_id'  => $product_id,
			'product'     => $product,
			'exclude_ids' => $exclude_ids,
			'order_id'    => isset( $context['order_id'] ) ? absint( $context['order_id'] ) : 0,
		);
	}
}
