<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Controller\Adminhtml\Sync;

use Exception;
use FiloBlu\Refilo\Model\Importer\Wishlist as WishlistImporter;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\View\Result\Redirect;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface as ResultInterfaceAlias;
use Throwable;

/**
 * @class Wishlist
 * @package FiloBlu\Refilo\Controller
 */
class Wishlist extends Action
{

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;
    /**
     * @var WishlistImporter
     */
    private $wishlistImporter;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param WishlistImporter $wishlistImporter
     */
    public function __construct(
        Context          $context,
        JsonFactory      $resultJsonFactory,
        WishlistImporter $wishlistImporter
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->wishlistImporter = $wishlistImporter;
        parent::__construct($context);
    }

    /**
     * @return Redirect|ResponseInterface|ResultInterfaceAlias
     */
    public function execute()
    {
        try {
            $this->wishlistImporter->execute();
            $this->messageManager->addSuccessMessage(__('Sync completed successfully!'));
        } catch (Throwable $throwable) {
            $this->messageManager->addErrorMessage(__("There was an error importing the MongoDB wishlists. Error: %s",
                $throwable->getMessage()));
        }

        /** @var Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        return $resultRedirect->setPath('adminhtml/system_config/edit/section/sync');
    }
}
