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

namespace WriteTextAI\WriteTextAI\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Authorization\Model\RoleFactory;
use Magento\Authorization\Model\ResourceModel\Role\CollectionFactory as RoleCollectionFactory;
use Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory as RulesCollectionFactory;

class ResetData extends Command
{
    /**
     * @var ResourceConnection
     */
    private $resource;

    /**
     * @var RoleFactory
     */
    private $roleFactory;

    /**
     * @var RoleCollectionFactory
     */
    private $roleCollectionFactory;

    /**
     * @var RulesCollectionFactory
     */
    private $rulesCollectionFactory;

    /**
     * Constructor.
     *
     * @param ResourceConnection $resource
     * @param RoleFactory $roleFactory
     * @param RoleCollectionFactory $roleCollectionFactory
     * @param RulesCollectionFactory $rulesCollectionFactory
     * @param string|null $name
     */
    public function __construct(
        ResourceConnection $resource,
        RoleFactory $roleFactory,
        RoleCollectionFactory $roleCollectionFactory,
        RulesCollectionFactory $rulesCollectionFactory,
        ?string $name = null
    ) {
        parent::__construct($name);
        $this->resource = $resource;
        $this->roleFactory = $roleFactory;
        $this->roleCollectionFactory = $roleCollectionFactory;
        $this->rulesCollectionFactory = $rulesCollectionFactory;
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this->setName('writetextai:data_reset')
             ->setDescription('Reset database data');
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $output->writeln('Start Reset');

            $timeStart = microtime(true);
            
            $connection = $this->resource->getConnection();
            $this->dropTables($connection);
            $this->deleteConfigData($connection);
            //$this->deleteUserRole($connection, $output);

            $timeLasted = ceil(microtime(true) - $timeStart);

            $output->writeln('End Reset, Time Lasted: ' . $timeLasted . ' secs');
        } catch (\Exception $e) {
            $output->writeln('Error: ' . $e->getMessage());
        }

        return 0;
    }

    /**
     * Drop tables
     *
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     */
    protected function dropTables($connection)
    {
        $tablesToDrop = [
            "writetextai_writetextai_products_store",
            "writetextai_writetextai_categories_store",
            "writetextai_writetextai_settings",
            "writetextai_writetextai_user_fields_selected",
            "writetextai_writetextai_user_web_token",
            "writetextai_writetextai_bulk_generate_requests",
            "writetextai_writetextai_bulk_transfer_requests",
            "writetextai_writetextai_bulk_keyword_analysis_requests",
            "writetextai_writetextai_user_feedback",
            "writetextai_writetextai_single_generate_requests",
            "writetextai_writetextai_product_reference_product",
            "writetextai_writetextai_product_keywords",
            "writetextai_writetextai_user_request_status",
            "writetextai_writetextai_product_keyword_ideas_filters",
            "writetextai_writetextai_product_keyword_ranked_filters",
            "writetextai_writetextai_product_keyword_competitor_filters"
        ];

        foreach ($tablesToDrop as $table) {
            $tableName = $this->resource->getTableName($table);
            if ($connection->isTableExists($tableName)) {
                $connection->truncateTable($tableName);
            }
        }
    }

    /**
     * Delete config data
     *
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     */
    protected function deleteConfigData($connection)
    {
        $configTable = $this->resource->getTableName('core_config_data');
        $connection->delete($configTable, "`path` LIKE 'writetextai_settings%'");
    }

    /**
     * Delete specific user role
     *
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     * @param OutputInterface $output
     */
    protected function deleteUserRole($connection, $output)
    {
        try {
            $roleName = 'Test new role';
            
            // Find the role by name
            $roleCollection = $this->roleCollectionFactory->create();
            $roleCollection->addFieldToFilter('role_name', $roleName);
            
            if ($roleCollection->getSize() > 0) {
                $role = $roleCollection->getFirstItem();
                $roleId = $role->getId();
                
                $output->writeln("Found role '{$roleName}' with ID: {$roleId}");
                
                // Delete associated rules first
                $rulesCollection = $this->rulesCollectionFactory->create();
                $rulesCollection->addFieldToFilter('role_id', $roleId);
                
                if ($rulesCollection->getSize() > 0) {
                    $rulesCollection->walk('delete');
                    $output->writeln("Deleted " . $rulesCollection->getSize() . " associated rules");
                }
                
                // Delete the role
                $role->delete();
                $output->writeln("Successfully deleted role '{$roleName}'");
            } else {
                $output->writeln("Role '{$roleName}' not found - skipping deletion");
            }
        } catch (\Exception $e) {
            $output->writeln("Error deleting user role: " . $e->getMessage());
        }
    }
}
