<?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 when an invoice is paid.
 *
 * Only active when "Confirm after an invoice created" is enabled, otherwise the
 * confirmation is sent on shipment by SalesOrderShipmentAfter.
 */
class SalesOrderInvoiceAfter 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
    {
        $invoice = $observer->getEvent()->getData('invoice');
        $order = $invoice?->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('Invoice confirmation, order %s: %s', $order->getIncrementId(), $e->getMessage())
            );
        }
    }
}
