<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Ui\Model\BookmarkFactory;

class UpgradeData implements UpgradeDataInterface
{
    public const CATEGORY_GRID_LISTING = 'wtai_categories_grid_listing';

    public const PRODUCT_GRID_LISTING = 'wtai_products_grid_listing';

    /**
     * @var BookmarkFactory
     */
    private $bookmarkFactory;

    /**
     * Constructor
     *
     * @param BookmarkFactory $bookmarkFactory
     */
    public function __construct(BookmarkFactory $bookmarkFactory)
    {
        $this->bookmarkFactory = $bookmarkFactory;
    }

    /**
     * Upgrade
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     *
     * @return void
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        // Reset listing filters
        $bookmarkCollection = $this->bookmarkFactory->create()->getCollection();
        $bookmarkCollection->addFieldToFilter('namespace', ['in' => [
            self::CATEGORY_GRID_LISTING,
            self::PRODUCT_GRID_LISTING
        ]]);
        $bookmarkCollection->walk('delete');

        // Force expiration of all user web tokens
        $setup->getConnection()->truncateTable(
            $setup->getTable('writetextai_writetextai_user_web_token')
        );

        // Refetch api settings
        $setup->getConnection()->truncateTable(
            $setup->getTable('writetextai_writetextai_settings')
        );

        $setup->endSetup();
    }
}
