<?php

declare (strict_types=1);
namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout;

use Automattic\WooCommerce\StoreApi\Utilities\CartController;
use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
use WC_Order;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\State\CheckoutSessionDataRepository;
/**
 * Creates WooCommerce orders using the Store API utilities.
 *
 * This implementation encapsulates all WooCommerce-specific order creation,
 * validation, and metadata application logic, keeping handlers clean.
 */
final class StoreApiOrderCreator implements CheckoutOrderCreatorInterface
{
    private CartController $cart_controller;
    private OrderController $order_controller;
    private CheckoutSessionDataRepository $session_data;
    public function __construct(CartController $cart_controller, OrderController $order_controller, CheckoutSessionDataRepository $session_data)
    {
        $this->cart_controller = $cart_controller;
        $this->order_controller = $order_controller;
        $this->session_data = $session_data;
    }
    public function create_from_cart(string $session_id, array $payment, array $platform): WC_Order
    {
        $this->cart_controller->calculate_totals();
        $this->cart_controller->validate_cart_not_empty();
        $this->cart_controller->validate_cart();
        $order = $this->order_controller->create_order_from_cart();
        $order->update_meta_data('_ucp_checkout_id', $session_id);
        if (!empty($payment)) {
            $order->update_meta_data('_ucp_payment', $payment);
        }
        $consent = $this->session_data->get_buyer_consent();
        if (null !== $consent) {
            $order->update_meta_data('_ucp_buyer_consent', $consent);
        }
        if (isset($platform['webhook_url'])) {
            $order->update_meta_data('_ucp_webhook_url', $platform['webhook_url']);
        }
        $order->set_created_via('ucp_checkout');
        $order->set_status('pending', 'Created via UCP checkout', \true);
        $order->save();
        $this->order_controller->validate_order_before_payment($order);
        \wc_reserve_stock_for_order($order);
        return $order;
    }
}
