<?php

namespace PaymentWebhooks\Core;

use PaymentWebhooks\Contract\OrderUpdaterInterface;
use PaymentWebhooks\Gateway\Common\OrderHelper;
use RuntimeException;
use WC_Order;

final class SynchronousOrderUpdater implements OrderUpdaterInterface
{
    public function update(?int $orderId, string $newStatus): void
    {
        $order = $this->getOrderOrFail($orderId);
        $order->update_status($newStatus);
    }

    public function updatePaymentData(?int $orderId, array $data): void
    {
        $order = $this->getOrderOrFail($orderId);
        if (isset($data['payment_method'])) {
            $order->set_payment_method($data['payment_method']);
        }
        if (isset($data['payment_method_title'])) {
            $order->set_payment_method_title($data['payment_method_title']);
        }
        if (isset($data['transaction_id'])) {
            $order->set_transaction_id($data['transaction_id']);
        }
        $order->save();
    }

    private function getOrderOrFail(?int $orderId): WC_Order
    {
        OrderHelper::checkOrderId($orderId);
        $order = wc_get_order($orderId);
        if (!$order instanceof WC_Order) {
            throw new RuntimeException('No Order found');
        }
        return $order;
    }

}
