<?php // phpcs:disable PSR1.Files.SideEffects.FoundWithSymbols

/** @noinspection PhpCSValidationInspection */

/*
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

declare(strict_types=1);

use Resursbank\Ecom\Lib\Model\PaymentHistory\Entry;
use Resursbank\Ecom\Lib\Model\PaymentHistory\Event;
use Resursbank\Ecom\Lib\Model\PaymentHistory\User;
use Resursbank\Ecom\Module\Payment\Repository as PaymentRepository;
use Resursbank\Ecom\Module\PaymentHistory\Repository as PaymentHistoryRepository;
use Resursbank\MerchantApi\Exception\InvalidDataException;
use Resursbank\MerchantApi\Repository\ResursbankOrderRepositoryFrontend;
use Resursbank\MerchantApi\Service\Cart as CartService;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Util\Translator;

// phpcs:disable
class ResursbankFailModuleFrontController extends ModuleFrontController
// phpcs:enable
{
    /**
     * Process failed order.
     *
     * @return void
     */
    public function postProcess(): void
    {
        try {
            $order = $this->getOrder();
            CartService::reinstate(order: $order);
            $this->errors[] = Translator::translate(
                phraseId: 'payment-failed-try-again'
            );

            // Attempt to resolve Resurs Bank order object from order.
            $resursbankOrder = ResursbankOrderRepositoryFrontend::findByOrderId(
                orderId: $order->id
            );

            if ($resursbankOrder === null) {
                Log::error(
                    message: 'Resursbank order not found. Order ID: ' . $order->id
                );
                return;
            }

            // Log the event in the payment history.
            $payment = PaymentRepository::get(
                $resursbankOrder->getMapiId()
            );

            PaymentHistoryRepository::write(entry: new Entry(
                paymentId: $payment->id,
                event: Event::REACHED_ORDER_FAILURE_PAGE,
                user: User::CUSTOMER
            ));
        } catch (Throwable $error) {
            // @todo Display an error page instead?
            $this->errors[] = Translator::translate(
                phraseId: 'payment-failed-cart-could-not-be-rebuilt'
            );
            Log::error(message: $error);
        }

        $this->redirectWithNotifications(
            'index.php?controller=order&step=1'
        );
    }

    /**
     * @throws InvalidDataException
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function getOrder(): Order
    {
        $orderId = (string) Tools::getValue('order_id');

        if ($orderId === '') {
            throw new InvalidDataException('No order ID provided.');
        }

        $order = new Order((int) $orderId);

        if (!Validate::isLoadedObject($order)) {
            throw new InvalidDataException('Order not found.');
        }

        return $order;
    }
}
