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

namespace WriteTextAI\WriteTextAI\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UninstallInterface;
use Magento\Framework\Module\Dir\Reader as ModuleDirReader;
use Magento\Framework\Filesystem\Driver\File;

class Uninstall implements UninstallInterface
{
    /**
     * @var ModuleDirReader
     */
    private $moduleDirReader;

    /**
     * @var File
     */
    private $file;

    /**
     * @param ModuleDirReader $moduleDirReader
     * @param File $file
     */
    public function __construct(
        ModuleDirReader $moduleDirReader,
        File $file
    ) {
        $this->moduleDirReader = $moduleDirReader;
        $this->file = $file;
    }

    /**
     * Uninstall module
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $this
            ->uninstallTables($setup)
            ->uninstallConfigData($setup);
    }

    /**
     * Uninstall tables
     *
     * @param SchemaSetupInterface $setup
     * @return $this
     */
    private function uninstallTables(SchemaSetupInterface $setup): self
    {
        $tablesToDrop = $this->getTablesFromWhitelist();

        foreach ($tablesToDrop as $table) {
            if ($setup->getConnection()->isTableExists($setup->getTable($table))) {
                $setup->getConnection()->dropTable(
                    $setup->getTable($table)
                );
            }
        }

        return $this;
    }

    /**
     * Get table names from db_schema_whitelist.json
     *
     * @return array
     */
    private function getTablesFromWhitelist(): array
    {
        try {
            $moduleDir = $this->moduleDirReader->getModuleDir('', 'WriteTextAI_WriteTextAI');
            $whitelistPath = $moduleDir . '/etc/db_schema_whitelist.json';
            
            if ($this->file->isExists($whitelistPath)) {
                $whitelistContent = $this->file->fileGetContents($whitelistPath);
                $whitelistData = json_decode($whitelistContent, true);
                
                if (is_array($whitelistData)) {
                    return array_keys($whitelistData);
                }
            }
        } catch (\Exception $e) {
            // Log the error but continue with fallback tables
            true; // suppresses empty catch warning
        }

        // Fallback to hardcoded table list if whitelist can't be read
        return $this->getHardcodedTables();
    }

    /**
     * Get hardcoded table names as fallback
     *
     * @return array
     */
    private function getHardcodedTables(): array
    {
        return [
            '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_full_automation_requests',
            'writetextai_writetextai_bulk_transfer_requests',
            'writetextai_writetextai_user_feedback',
            'writetextai_writetextai_bulk_keyword_analysis_requests',
            'writetextai_writetextai_single_generate_requests',
            'writetextai_writetextai_new_records'
        ];
    }

    /**
     * Uninstall config data
     *
     * @param SchemaSetupInterface $setup
     * @return $this
     */
    private function uninstallConfigData(SchemaSetupInterface $setup): self
    {
        $configTable = $setup->getTable('core_config_data');
        $setup->getConnection()->delete($configTable, "`path` LIKE 'writetextai_settings%'");

        return $this;
    }
}
