<?php
namespace FuseCommerce;

if ( ! defined( 'ABSPATH' ) ) exit;

use FuseCommerce\Config\IndexingConfig;
use FuseCommerce\Hooks\HooksFactory;
use FuseCommerce\Jobs\Cron;
use FuseCommerce\Utils\OptionUtils;

class App {
    static function run(mixed $file): void {
        HooksFactory::registerHooks();
        register_activation_hook(
            $file,
            [self::class, 'onActivate']
        );
        
        register_uninstall_hook(
            $file,
            [self::class, 'onUninstall']
        );
    }

    static function onActivate(): void {
        Cron::addCronJobs();
    }

    static function onUninstall(): void {
        self::cleanupWordPressOptions();
        self::cleanupFileSystem();
        self::cleanupTemporaryFiles();
        self::cleanupCronJobs();
    }

    /**
     * Clean up WordPress options
     */
    private static function cleanupWordPressOptions(): void {
        try {
            delete_option(OptionUtils::OPTION_GROUP_SLUG);
        } catch (\Throwable $th) {
            error_log('FtlCommerce cleanup: Failed to delete settings - ' . $th->getMessage());
        }

        try {
            delete_option(IndexingConfig::INDEXING_STATE_OPTION_KEY);
        } catch (\Throwable $th) {
            error_log('FtlCommerce cleanup: Failed to delete indexing state - ' . $th->getMessage());
        }

        try {
            delete_option(IndexingConfig::INDEXING_LAST_STATE_OPTION_KEY);
        } catch (\Throwable $th) {
            error_log('FtlCommerce cleanup: Failed to delete last state - ' . $th->getMessage());
        }
    }

    /**
     * Clean up file system storage
     */
    private static function cleanupFileSystem(): void {
        try {
            $storage_dir = IndexingConfig::getStorageDir();

            // Use WP_Filesystem for safe directory removal
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
            global $wp_filesystem;

            if ($wp_filesystem && $wp_filesystem->is_dir($storage_dir)) {
                $wp_filesystem->delete($storage_dir, true); // true = recursive
            }
        } catch (\Throwable $th) {
            error_log('FtlCommerce cleanup: Failed to delete storage directory - ' . $th->getMessage());
        }
    }

    /**
     * Clean up temporary files
     */
    private static function cleanupTemporaryFiles(): void {
        try {
            $lock_file = get_temp_dir() . 'fusecommerce_index_products.lock';
            if (file_exists($lock_file)) {
                wp_delete_file($lock_file);
            }
        } catch (\Throwable $th) {
            error_log('FtlCommerce cleanup: Failed to delete lock file - ' . $th->getMessage());
        }
    }

    /**
     * Clean up cron jobs
     */
    private static function cleanupCronJobs(): void {
        Cron::removeCronJobs();
    }
}