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

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

            if (!$payment->canCapture()) {
                throw new PaymentException(
                    message: Translator::translate(phraseId: 'payment-cannot-be-captured')
                );
            }

            // Capture via Resurs Bank API
            $captured = Repository::capture(paymentId: $payment->id);
            $capturedAmount = $captured->order->capturedAmount - $payment->order->capturedAmount;

            if ($capturedAmount <= 0) {
                throw new PaymentException(message: 'No new amount captured.');
            }

            // Success feedback to user
            $this->session->getFlashBag()->add(
                type: 'success',
                message: sprintf(
                    Translator::translate(phraseId: 'capture-success'),
                    Price::format(value: $capturedAmount)
                )
            );

            // Update PrestaShop order status
            $this->setOrderStatus(request: $request, status: Order::ORDER_STATE_PAID);

            // Get PrestaShop order object
            $order = $this->getOrder(request: $request);

            if (!Order::hasPayment(order: $order)) {
                // Use the existing service to create and link invoice/payment
                Order::createInvoice(
                    payment: $payment,
                    order: $order,
                    capturedAmount: $capturedAmount
                );
            }
        } catch (Exception $e) {
            Log::error(message: $e);
            $this->session->getFlashBag()->add(
                type: 'error',
                message: Translator::translate(phraseId: 'failed-to-capture-payment') . ' (' . $e->getMessage() . ')'
            );
        }

        return $this->redirectBack();
    }
}
