<?php

namespace App\Console\Commands\Extensions;

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

class DisableCommand extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'extension:disable {id : The extension ID to disable}';

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

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

        $this->info("Disabling extension: {$extensionId}");

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

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

            if (!$extension->enabled) {
                $this->warn("Extension '{$extensionId}' is already disabled!");
                return 0;
            }

            // Load extension class
            $extensionClass = $this->findExtensionClass($extensionId);
            if (!$extensionClass) {
                $this->error("Extension class not found for '{$extensionId}'");
                return 1;
            }

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

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

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

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

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

            $this->newLine();
            $this->info("✓ Extension '{$extensionId}' disabled successfully!");

            return 0;

        } catch (\Exception $e) {
            $this->error('Disable 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}");
    }
}
