<?php
/**
 * Validates manual product/variation assignments from the review table.
 *
 * @package EmberPrice
 */

namespace EmberPrice\Rest;

defined( 'ABSPATH' ) || exit;

/**
 * Keeps invalid ids and unrelated variations out of learned aliases.
 */
final class ProductAssignmentValidator {

	/**
	 * Validates one manual WooCommerce assignment.
	 *
	 * @param int      $product_id   Parent/simple product id.
	 * @param int|null $variation_id Variation id when pricing a variation.
	 *
	 * @return \WP_Error|null Null when valid.
	 */
	public function validate( int $product_id, ?int $variation_id ): ?\WP_Error {
		if ( $product_id <= 0 || ( null !== $variation_id && $variation_id <= 0 ) ) {
			return new \WP_Error( 'embp_invalid_product', __( 'Choose a valid WooCommerce product.', 'emberprice' ) );
		}

		// The lightweight PHPUnit integration bootstrap intentionally does
		// not load WooCommerce. Production cannot reach this branch because
		// the plugin requires active WooCommerce before booting its routes.
		if ( ! function_exists( 'wc_get_product' ) ) {
			return null;
		}

		$product = wc_get_product( $product_id );

		if ( ! $product instanceof \WC_Product || 'trash' === $product->get_status() ) {
			return new \WP_Error( 'embp_product_not_found', __( 'The selected WooCommerce product no longer exists.', 'emberprice' ) );
		}

		if ( null === $variation_id ) {
			if ( $product instanceof \WC_Product_Variable || $product instanceof \WC_Product_Variation ) {
				return new \WP_Error( 'embp_variation_required', __( 'Choose a concrete variation for variable products.', 'emberprice' ) );
			}

			return null;
		}

		$variation = wc_get_product( $variation_id );

		if (
			! $variation instanceof \WC_Product_Variation
			|| $variation->get_parent_id() !== $product_id
			|| 'trash' === $variation->get_status()
		) {
			return new \WP_Error( 'embp_invalid_variation', __( 'The selected variation does not belong to this product.', 'emberprice' ) );
		}

		return null;
	}
}
