<?php
declare(strict_types=1);

namespace Autogedal\PayPo\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use PayPo\Payment\Model\Payment\PayPo;

class SetWaitingStatusOnPlace implements ObserverInterface
{
    private const STATUS_WAITING = 'asteptare_plata_paypo';

    public function __construct(
        private readonly OrderRepositoryInterface $orderRepository
    ) {
    }

    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;
        }

        // checkout_submit_all_after fires after payment processing and after the first
        // save, so this is the last chance to override status before email is sent.
        $order->setStatus(self::STATUS_WAITING);
        $this->orderRepository->save($order);
    }
}
