<?php

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

use Automattic\WooCommerce\StoreApi\Payments\PaymentContext;
use Automattic\WooCommerce\StoreApi\Payments\PaymentResult as StoreApiPaymentResult;
use Exception;
use WC_Order;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Payment\PaymentResult;
/**
 * Adapter that executes payments using the official WooCommerce Store API hook.
 *
 * This isolates the domain from the WooCommerce REST API context and avoids
 * needing to inherit CheckoutTrait in domain command handlers.
 */
final class StoreApiPaymentExecutor
{
    /**
     * Executes a payment through the Store API flow.
     *
     * @param WC_Order              $order        The order to pay for.
     * @param string                $gateway_id   The ID of the WooCommerce payment gateway (e.g. 'woocommerce_payments').
     * @param array<string, mixed>  $payment_data The raw payment data expected by the gateway (mapped to $_POST internally by WC).
     *
     * @return PaymentResult Domain payment result.
     */
    public function execute(WC_Order $order, string $gateway_id, array $payment_data): PaymentResult
    {
        if (!\class_exists(PaymentContext::class)) {
            return PaymentResult::failed('WooCommerce Store API is not available.');
        }
        $context = new PaymentContext();
        $context->set_payment_method($gateway_id);
        $context->set_payment_data($payment_data);
        $context->set_order($order);
        $store_api_result = new StoreApiPaymentResult();
        try {
            /**
             * Process payment with context.
             * This is the official Store API hook that handles the legacy gateway fallback
             * (mapping payment_data to $_POST) and fires the gateway's process_payment method.
             */
            \do_action_ref_array('woocommerce_rest_checkout_process_payment_with_context', [$context, &$store_api_result]);
            if ('success' === $store_api_result->status) {
                // @phpstan-ignore property.protected
                return PaymentResult::success($order->get_transaction_id() ?? '');
            }
            $message = $store_api_result->payment_details['errorMessage'] ?? 'Payment was declined by the gateway.';
            return PaymentResult::failed(\wp_strip_all_tags($message));
        } catch (Exception $e) {
            return PaymentResult::failed(\wp_strip_all_tags($e->getMessage()));
        }
    }
}
