<?php

namespace Easymailing\App\Core\Provider\Woocommerce\Service;

use Easymailing\App\Core\Provider\Woocommerce\Exception\CustomerNotFoundException;
use Easymailing\App\Core\Provider\Woocommerce\Exception\ProductOrVariantNotFoundException;

class OrderValidator
{
	public function validateOrder(\WC_Order $order): void
	{
		// Validar si el usuario asignado a la orden existe en WordPress
		$customerId = $order->get_customer_id();
		if ($customerId && !get_user_by('id', $customerId)) {
			throw new CustomerNotFoundException(
				$order->get_id(),
				$customerId,
				sprintf("Customer ID %s not found in WordPress", $customerId)
			);
		}

		// Validar los productos y variaciones de la orden
		foreach ($order->get_items() as $item) {
			$productId = $item->get_product_id();
			$variationId = $item->get_variation_id();

			// Verificar si el producto existe
			$product = wc_get_product($productId);
			if (!$product || $product->get_status() === 'trash') {
				throw new ProductOrVariantNotFoundException(
					$order->get_id(),
					$productId,
					null,
					sprintf("Product ID %s not found or trashed in WooCommerce", $productId)
				);
			}

			// Verificar si la variante existe (si aplica)
			if ($variationId) {
				$variation = wc_get_product($variationId);
				if (!$variation || !$variation->is_type('variation') || $variation->get_status() === 'trash') {
					throw new ProductOrVariantNotFoundException(
						$order->get_id(),
						$productId,
						$variationId,
						sprintf("Variant ID %s not found or trashed in WooCommerce", $variationId)
					);
				}
			}
		}
	}
}
