<?php
declare(strict_types=1);

namespace PayPo\Payment\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order;
use PayPo\Payment\Helper\Data;
use PayPo\Payment\Model\Payment\PayPo;

/**
 * Applies the configured "New Order Status" to freshly placed PayPo orders.
 */
class ChangeStatusAfterPlace implements ObserverInterface
{
    /**
     * @param Data $helper
     */
    public function __construct(
        private readonly Data $helper
    ) {
    }

    /**
     * The event is dispatched from Order::place(), before the order is saved,
     * so setting the status is enough - no explicit save is needed here.
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        /** @var Order|null $order */
        $order = $observer->getEvent()->getData('order');

        if (!$order instanceof Order || $order->getPayment()?->getMethod() !== PayPo::METHOD_CODE) {
            return;
        }

        $status = (string)$this->helper->getConfig('order_status', $order->getStoreId());

        if ($status !== '') {
            $order->setStatus($status);
        }
    }
}
