<?php

namespace PaymentWebhooks\Core;

use PaymentWebhooks\Infrastructure\Config;
use PaymentWebhooks\Infrastructure\Logger;
use WC_Order;

class OrderStatusUpdater
{
    private const ASYNC_DELAY = 5;

    public function update(?int $orderId, string $newStatus): bool
    {
        if ($this->isNotCorrectOrderId($orderId)) {
            return false;
        }

        $async = Config::get('PW_ASYNC_UPDATE', false);

        if ($async && function_exists('as_schedule_single_action')) {
            if (!as_has_scheduled_action('pw_update_order', [$orderId, $newStatus], 'pw')) {
                as_schedule_single_action(
                    time() + self::ASYNC_DELAY,
                    'pw_update_order',
                    [$orderId, $newStatus],
                    'pw'
                );
            }
            return true;
        }

        $order = wc_get_order($orderId);
        if (!$order instanceof WC_Order) {
            return false;
        }

        $order->update_status($newStatus);
        return true;
    }

    private function isNotCorrectOrderId(?int $orderId): bool
    {
        return $orderId === null || $orderId <= 0;
    }

}

// Register the Action Scheduler hook
add_action('pw_update_order', static function (int $orderId, string $newStatus) {
    $logger = Logger::forGateway('adyen');

    $order = wc_get_order($orderId);
    if (!$order instanceof WC_Order) {
        $logger->warning('Async: order not found', ['order_id' => $orderId]);
        return;
    }

    $order->update_status($newStatus);
    $logger->info('Async: order status updated', ['order_id' => $orderId, 'status' => $newStatus]);
}, 10, 2);
