<?php
declare(strict_types=1);

namespace PayPo\Payment\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use PayPo\Payment\Helper\Data;
use PayPo\Payment\Logger\Logger;
use PayPo\Payment\Model\Payment\PayPo;
use PayPo\Payment\Model\PayPoApi;

/**
 * Confirms the PayPo transaction once the order has been shipped.
 *
 * This is the default confirmation moment; when "Confirm after an invoice
 * created" is enabled the confirmation is sent by SalesOrderInvoiceAfter instead.
 */
class SalesOrderShipmentAfter implements ObserverInterface
{
    /**
     * @param PayPoApi $paypoApi
     * @param Data $helper
     * @param Logger $paypoLogger
     */
    public function __construct(
        private readonly PayPoApi $paypoApi,
        private readonly Data $helper,
        private readonly Logger $paypoLogger
    ) {
    }

    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        $shipment = $observer->getEvent()->getData('shipment');
        $order = $shipment?->getOrder();
        $payment = $order?->getPayment();

        if ($payment === null || $payment->getMethod() !== PayPo::METHOD_CODE) {
            return;
        }

        if ($this->helper->autoApproveInvoice($order->getStoreId())) {
            return;
        }

        $method = $payment->getMethodInstance();
        $orderTransaction = $method instanceof PayPo ? $method->getOrderTransaction($payment) : false;

        if (!$orderTransaction) {
            return;
        }

        try {
            $this->paypoApi->changeStatus(
                (string)$orderTransaction->getTxnId(),
                PayPoApi::STATUS_COMPLETED,
                $order->getStoreId()
            );
        } catch (\Exception $e) {
            $this->paypoLogger->addError(
                sprintf('Shipment confirmation, order %s: %s', $order->getIncrementId(), $e->getMessage())
            );
        }
    }
}
