<?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\Plugin;

use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Layout\ProcessorInterface;
use Mirasvit\CacheWarmer\Model\Config\Source\PageCacheable;
use Mirasvit\CacheWarmer\Service\Config\ExtendedConfig;

class DeleteCacheableFalsePlugin
{
    const ALLOWED_ACTIONS = [
            'cms_index_index',
            'catalog_product_view',
            'catalog_category_view',
        ];

    const CACHEABLE_FALSE = 'cacheable="false"';

    private $request;

    private $extendedConfig;

    public function __construct(
        ExtendedConfig $extendedConfig,
        RequestInterface $request
    ){
        $this->extendedConfig = $extendedConfig;
        $this->request        = $request;
    }

    public function afterAsString(ProcessorInterface $subject, string $updates): string
    {
        if ($this->extendedConfig->isDeleteCacheableFalse() == PageCacheable::PAGE_CACHEABLE_CONFIGURE) {
            $allowedActions = $this->extendedConfig->getDeleteCacheableFalseConfig();
        } else {
            $allowedActions = self::ALLOWED_ACTIONS;
        }
        if ($this->extendedConfig->isDeleteCacheableFalse()
            && in_array($this->request->getFullActionName(), $allowedActions)) {
            $updates = str_replace(self::CACHEABLE_FALSE, '', $updates);
        }

        return $updates;
    }
}
