<?php

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

declare(strict_types=1);

namespace Resursbank\MerchantApi\Controller\Admin\Order;

use JsonException;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use ReflectionException;
use Resursbank\Ecom\Config;
use Resursbank\Ecom\Exception\ApiException;
use Resursbank\Ecom\Exception\AttributeCombinationException;
use Resursbank\Ecom\Exception\AuthException;
use Resursbank\Ecom\Exception\ConfigException;
use Resursbank\Ecom\Exception\CurlException;
use Resursbank\Ecom\Exception\FilesystemException;
use Resursbank\Ecom\Exception\Validation\EmptyValueException;
use Resursbank\Ecom\Exception\Validation\IllegalTypeException;
use Resursbank\Ecom\Exception\Validation\IllegalValueException;
use Resursbank\Ecom\Exception\ValidationException;
use Resursbank\Ecom\Lib\Model\Widget\ReloadWidgetResponse;
use Resursbank\Ecom\Module\Widget\PaymentInformation\Html as PaymentInformation;
use Resursbank\MerchantApi\Util\Log;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

/**
 * Reload payment information widget.
 */
class ReloadPaymentInformation extends FrameworkBundleAdminController
{
    /**
     * Execute request to reload payment information widget. Note that
     * exceptions are handled by the catch block supplied by the JS widget.
     *
     * @param Request $request
     * @return JsonResponse
     * @throws Throwable
     * @throws JsonException
     * @throws ReflectionException
     * @throws ApiException
     * @throws AttributeCombinationException
     * @throws AuthException
     * @throws ConfigException
     * @throws CurlException
     * @throws FilesystemException
     * @throws ValidationException
     * @throws EmptyValueException
     * @throws IllegalTypeException
     * @throws IllegalValueException
     */
    public function execute(
        Request $request
    ): JsonResponse {
        try {
            $mapiId = $request->get(key: 'mapi_id');

            $widget = new PaymentInformation(
                paymentId: $mapiId,
            );

            return JsonResponse::create(
                data: new ReloadWidgetResponse(
                    html: $widget->content
                )
            );
        } catch (Throwable $error) {
            Log::error(message: $error);
            throw $error;
        }
    }
}
