<?php

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

declare(strict_types=1);

namespace Resursbank\MerchantApi\Controller\Admin\Config;

use Context;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Util\Translator;
use Resursbank\MerchantApi\Service\CallbackTest as CallbackTestService;
use Symfony\Component\HttpFoundation\JsonResponse;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

/**
 * Callback test controller
 */
class CallbackTest extends FrameworkBundleAdminController
{
    /**
     * @param CallbackTestService $callbackTestService
     */
    public function __construct(
        private readonly CallbackTestService $callbackTestService
    ) {
        parent::__construct();
    }

    /**
     * Process incoming request and trigger callback test.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function execute(
        Request $request
    ): JsonResponse {
        try {
            $link = Context::getContext()->link->getModuleLink(
                module: 'resursbank',
                controller: 'callbacktest'
            );

            $this->callbackTestService->triggerTest(
                targetUrl: $link
            );
            $message = Translator::translate(
                phraseId: 'test-callback-was-sent'
            );
        } catch (Throwable $error) {
            Log::error(message: $error);
            $message = Translator::translate(
                phraseId: 'test-callback-could-not-be-triggered'
            );
        }

        return new JsonResponse(
            data: json_encode(
                value: [
                    'message' => $message
                ]
            )
        );
    }
}
