<?php

namespace App\Console\Commands\Extensions;

use App\Models\Extension;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UninstallCommand extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'extension:uninstall {id : The extension ID to uninstall} {--force : Force uninstallation without confirmation}';

    /**
     * The console command description.
     */
    protected $description = 'Uninstall an extension';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $extensionId = $this->argument('id');
        $force = $this->option('force');

        try {
            // Find extension record
            $extension = Extension::where('extension_id', $extensionId)->first();

            if (!$extension) {
                $this->error("Extension '{$extensionId}' not found in database!");
                $this->line('Run: php artisan extension:list --available to see available extensions');
                return 1;
            }

            // Check if installed
            if (!$extension->installed) {
                $this->warn("Extension '{$extensionId}' is not installed!");
                return 1;
            }

            // Confirm uninstallation
            if (!$force) {
                $this->warn("⚠️  Warning: This will remove all data associated with '{$extensionId}'");
                $this->line('  • Database tables will be dropped');
                $this->line('  • Extension files will remain but be marked as uninstalled');
                $this->line('  • Settings and configurations will be lost');
                $this->newLine();

                if (!$this->confirm('Are you sure you want to uninstall this extension?', false)) {
                    $this->info('Uninstallation cancelled.');
                    return 0;
                }
            }

            // Load extension class
            $extensionClass = $this->findExtensionClass($extensionId);
            if (!$extensionClass) {
                $this->error("Extension class not found for '{$extensionId}'");
                $this->warn('Extension will be marked as uninstalled in database only.');
                $extension->update(['installed' => false, 'enabled' => false]);
                return 1;
            }

            // Get extension path
            $extensionPath = $this->getExtensionPath($extensionId);

            // Instantiate extension with path
            $instance = new $extensionClass($extensionPath);

            // Set extension context using reflection
            $reflection = new \ReflectionClass($instance);
            $property = $reflection->getProperty('extension');
            $property->setAccessible(true);
            $property->setValue($instance, $extension);

            // Disable first if enabled
            if ($extension->enabled) {
                $this->info('Disabling extension first...');
                $instance->disable();
                $extension->update(['enabled' => false]);
            }

            // Run uninstall method
            $this->info('Running uninstallation process...');
            $instance->uninstall();

            // Mark as uninstalled
            $extension->update([
                'installed' => false,
                'enabled' => false,
            ]);

            $this->newLine();
            $this->info("✓ Extension '{$extensionId}' uninstalled successfully!");
            $this->newLine();
            $this->info('The extension files remain in place and can be reinstalled with:');
            $this->line("  php artisan extension:install {$extensionId}");

            return 0;

        } catch (\Exception $e) {
            $this->error('Uninstallation failed: ' . $e->getMessage());
            $this->newLine();
            $this->error('Stack trace:');
            $this->line($e->getTraceAsString());
            return 1;
        }
    }

    /**
     * Find the extension class file.
     */
    protected function findExtensionClass(string $extensionId): ?string
    {
        // Convert kebab-case to StudlyCase (e.g., live-chat -> LiveChat)
        $className = str_replace('-', '', ucwords($extensionId, '-'));

        $path = app_path("Extensions/Installed/{$className}/{$className}Extension.php");

        if (!File::exists($path)) {
            return null;
        }

        $class = "App\\Extensions\\Installed\\{$className}\\{$className}Extension";

        if (!class_exists($class)) {
            return null;
        }

        return $class;
    }

    /**
     * Get the extension directory path.
     */
    protected function getExtensionPath(string $extensionId): string
    {
        // Convert kebab-case to StudlyCase (e.g., live-chat -> LiveChat)
        $className = str_replace('-', '', ucwords($extensionId, '-'));
        return app_path("Extensions/Installed/{$className}");
    }
}
