<?php
declare(strict_types=1);

namespace Autogedal\EanTools\Controller\Adminhtml\Stats;

use Autogedal\EanTools\Controller\Adminhtml\AbstractTool;
use Autogedal\EanTools\Model\StatsSnapshot;
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 Refresh extends AbstractTool implements HttpPostActionInterface
{
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        private readonly StatsSnapshot $snapshot,
        private readonly LoggerInterface $logger
    ) {
        parent::__construct($context, $resultPageFactory);
    }

    public function execute(): ResultInterface
    {
        try {
            $this->snapshot->requestRefresh();
            $this->messageManager->addSuccessMessage(
                (string)__('The data recalculation has been queued and will be processed by cron.')
            );
        } catch (LocalizedException $e) {
            $this->logger->warning('Autogedal_EanTools stats refresh: ' . $e->getMessage(), ['exception' => $e]);
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (Throwable $e) {
            $this->logger->error('Autogedal_EanTools stats refresh: ' . $e->getMessage(), ['exception' => $e]);
            $this->messageManager->addErrorMessage((string)__('The statistics could not be recalculated.'));
        }

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