<?php
/**
 * Mirasvit
 *
 * This source file is subject to the Mirasvit Software License, which is available at https://mirasvit.com/license/.
 * Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please refer to http://www.magentocommerce.com for more information.
 *
 * @category  Mirasvit
 * @package   mirasvit/module-cache-warmer
 * @version   1.11.13
 * @copyright Copyright (C) 2026 Mirasvit (https://mirasvit.com/)
 */


declare(strict_types=1);


namespace Mirasvit\CacheWarmer\Controller\Warmer;


use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Mirasvit\CacheWarmer\Api\Data\PageInterface;
use Mirasvit\CacheWarmer\Repository\PageRepository;
use Mirasvit\CacheWarmer\Service\WarmerService;
use Mirasvit\Core\Service\SerializeService;

class CleanCache extends Action
{
    private $warmerService;

    private $pageRepository;

    public function __construct(
        WarmerService $warmerService,
        PageRepository $pageRepository,
        Context $context
    ) {
        $this->warmerService  = $warmerService;
        $this->pageRepository = $pageRepository;

        parent::__construct($context);
    }

    public function execute()
    {
        $response = $this->getResponse();

        $pageId = $this->getRequest()->getParam(PageInterface::ID);

        if (!$pageId) {
            return $response->representJson(SerializeService::encode([
                'success' => false,
                'message' => __('%1 is not set', PageInterface::ID),
            ]));
        }

        $page = $this->pageRepository->get($pageId);

        if (!$page) {
            return $response->representJson(SerializeService::encode([
                'success' => false,
                'message' => __('Page with ID %1 does not exist', $pageId),
            ]));
        }

        $this->warmerService->cleanPage($page);

        return $response->representJson(SerializeService::encode([
            'success' => true,
            'message' => $pageId,
        ]));
    }
}
