<?php
declare(strict_types=1);

namespace Autogedal\EanTools\Controller\Adminhtml\Duplicates;

use Autogedal\EanTools\Controller\Adminhtml\AbstractFormatTool;
use Autogedal\EanTools\Model\Spreadsheet\Format;
use Autogedal\EanTools\Model\Tool\ExportScheduler;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Result\PageFactory;
use Psr\Log\LoggerInterface;
use Throwable;

class Export extends AbstractFormatTool implements HttpPostActionInterface
{
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Format $format,
        private readonly ExportScheduler $scheduler,
        private readonly LoggerInterface $logger
    ) {
        parent::__construct($context, $resultPageFactory, $format);
    }

    public function execute(): ResultInterface
    {
        try {
            $runId = $this->scheduler->scheduleDuplicates($this->resolveFormat());
            $this->messageManager->addSuccessMessage(
                (string)__('The export has been queued and will be processed by cron.')
            );

            return $this->redirectTo('*/result/index', ['run' => $runId]);
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (Throwable $e) {
            $this->logger->error('Autogedal_EanTools duplicates export: ' . $e->getMessage(), ['exception' => $e]);
            $this->messageManager->addErrorMessage((string)__('The export of duplicate EANs could not be generated.'));
        }

        return $this->redirectTo('*/index/index');
    }
}
