<?php

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

declare(strict_types=1);

namespace Resursbank\MerchantApi\Controller\Admin\Order;

use Exception;
use Resursbank\Ecom\Lib\Utilities\Price;
use Resursbank\Ecom\Module\Payment\Repository;
use Resursbank\MerchantApi\Exception\PaymentException;
use Resursbank\MerchantApi\Service\Order;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Util\Translator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Cancel entire, remaining, payment at Resurs Bank.
 */
class Cancel extends Aftershop
{
    /**
     * Cancel payment.
     */
    public function execute(Request $request): RedirectResponse
    {
        try {
            $payment = $this->getMapiPayment(request: $request);
            $order = $this->getOrder(request: $request);

            if (!$payment->canCancel() ||
                !Order::isResursbank(orderReference: $order->reference)
            ) {
                throw new PaymentException(
                    message: Translator::translate('payment-cannot-be-cancelled')
                );
            }

            $payment2 = Repository::cancel(paymentId: $payment->id);

            $this->session->getFlashBag()->add(
                type: 'success',
                message: sprintf(
                    Translator::translate('cancel-success'),
                    Price::format($payment2->order->canceledAmount - $payment->order->canceledAmount)
                )
            );

            $this->setOrderStatus(request: $request, status: Order::ORDER_STATE_CANCELED);
        } catch (Exception $e) {
            Log::error(message: $e);
            $this->session->getFlashBag()->add(
                type: 'error',
                message: Translator::translate('failed-to-cancel-payment') . ' (' . $e->getMessage() . ')'
            );
        }

        return $this->redirectBack();
    }
}
