<?php

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

use WC_Order;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Payment\PaymentHandlerInterface;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Payment\PaymentResult;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\State\CheckoutStateRepository;
/**
 * Orchestrates UCP payment execution with session locking and state management.
 */
final class LockedCheckoutPaymentExecutor implements CheckoutPaymentExecutorInterface
{
    private CheckoutStateRepository $state;
    public function __construct(CheckoutStateRepository $state)
    {
        $this->state = $state;
    }
    public function execute_payment(WC_Order $order, PaymentHandlerInterface $processor, array $instrument): PaymentResult
    {
        $this->state->lock_payment();
        try {
            $payment_result = $processor->process($order, $instrument);
            if (!$payment_result->is_success()) {
                $order->update_status('failed', \sprintf('UCP Payment failed: %s', $payment_result->get_error()));
                return $payment_result;
            }
            $this->state->mark_completed((int) $order->get_id());
            return $payment_result;
        } finally {
            $this->state->unlock_payment();
        }
    }
}
