<?php
declare(strict_types=1);

namespace Autogedal\PayPo\Plugin;

use Autogedal\PayPo\Model\PayPoContext;
use Autogedal\PayPo\Model\ApprovalConfig;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\Handler\State;

class ApprovalStatePlugin
{
    public function __construct(
        private readonly PayPoContext $payPoContext,
        private readonly ApprovalConfig $approvalConfig
    ) {
    }

    public function beforeCheck(State $subject, Order $order): array
    {
        if ($this->payPoContext->appliesToOrder($order->getId())
            && $this->approvalConfig->isOrderAllowed($order, true)
        ) {
            // Keep payment bookkeeping without advancing the warehouse workflow.
            $order->setState('pending')->setStatus('new');
        }

        return [$order];
    }
}
