<?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/)
 */



namespace Mirasvit\CacheWarmer\Setup\Patch\Data;

use Magento\Config\Model\ResourceModel\Config as ConfigWriter;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Mirasvit\CacheWarmer\Api\Service\WarmerServiceInterface;

class DataPatch1019 implements DataPatchInterface
{
    private $setup;

    private $configWriter;

    public function __construct(
        ModuleDataSetupInterface $setup,
        ConfigWriter $configWriter
    ) {
        $this->setup        = $setup;
        $this->configWriter = $configWriter;
    }

    /**
     * @inheritdoc
     */
    public function apply()
    {
        $this->setup->getConnection()->startSetup();

        $connection  = $this->setup->getConnection();
        $configTable = $this->setup->getTable('core_config_data');

        $existing = $connection->fetchOne(
            $connection->select()
                ->from($configTable, ['value'])
                ->where('path = ?', WarmerServiceInterface::WARMER_UNIQUE_VALUE)
                ->where('scope = ?', ScopeConfigInterface::SCOPE_TYPE_DEFAULT)
                ->where('scope_id = ?', 0)
        );

        if (empty($existing)) {
            $this->configWriter->saveConfig(
                WarmerServiceInterface::WARMER_UNIQUE_VALUE,
                bin2hex(random_bytes(16)),
                ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
                0
            );
        }

        $this->setup->getConnection()->endSetup();
    }

    /**
     * @inheritdoc
     */
    public static function getDependencies(): array
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function getAliases(): array
    {
        return [];
    }
}
