<?php

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

declare(strict_types=1);

namespace Resursbank\MerchantApi\Controller\Admin\Config;

use Exception;
use Module;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use resursbank;
use Resursbank\MerchantApi\Config\Form\DataProvider;
use Resursbank\MerchantApi\Exception\ConfigException;
use Resursbank\MerchantApi\Logger\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

use function count;
use function is_array;

/**
 * Sync data from Resurs Bank API to local database.
 */
class Save extends FrameworkBundleAdminController
{
    /**
     * @var resursbank
     */
    private resursbank $module;

    /**
     * @param LoggerInterface $logger
     * @param DataProvider $dataProvider
     */
    public function __construct(
        private readonly LoggerInterface $logger,
        private readonly DataProvider $dataProvider
    ) {
        parent::__construct();

        $this->module = Module::getInstanceByName(module_name: 'resursbank');
    }

    /**
     * Fetch payment methods from API and sync them to database.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function execute(
        Request $request
    ): RedirectResponse {
        try {
            $data = $request->get('form');

            if (!is_array($data)) {
                throw new ConfigException('Invalid or missing form data.');
            }

            $errors = $this->dataProvider->setData($data);

            if (count($errors) > 0) {
                $this->flashErrors($errors);
            } else {
                $this->addFlash(
                    'success',
                    $this->module->l('Successful update.')
                );
            }
        } catch (Exception $e) {
            // @todo Not sure if this is really safe?
            $this->addFlash('error', $e->getMessage());
            $this->logger->exception($e);
        }

        return $this->redirectToRoute('resursbank_admin_config');
    }
}
