<?php

namespace FluxCms\Core\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class InstallCommand extends Command
{
    protected $signature = 'flux-cms:install
                            {--force : Overwrite existing files}
                            {--no-migrate : Skip running migrations}
                            {--no-publish : Skip publishing assets}';

    protected $description = 'Install Flux CMS';

    public function handle(): int
    {
        $this->info('🚀 Installing Flux CMS...');

        // Check requirements
        if (! $this->checkRequirements()) {
            return 1;
        }

        // Publish configuration
        if (! $this->option('no-publish')) {
            $this->publishAssets();
        }

        // Run migrations
        if (! $this->option('no-migrate')) {
            $this->runMigrations();
        }

        // Create storage link if needed
        $this->createStorageLink();

        // Create sample content
        $this->createSampleContent();

        // Set permissions
        $this->setPermissions();

        $this->info('✅ Flux CMS installed successfully!');
        $this->showNextSteps();

        return 0;
    }

    protected function checkRequirements(): bool
    {
        $this->info('🔍 Checking requirements...');

        $requirements = [
            'PHP 8.2+' => version_compare(PHP_VERSION, '8.2.0', '>='),
            'Laravel 11+' => $this->checkLaravelVersion(),
            'Livewire 3+' => $this->checkLivewireVersion(),
            'Spatie Translatable' => class_exists(\Spatie\Translatable\HasTranslations::class),
            'Spatie Media Library' => class_exists(\Spatie\MediaLibrary\HasMedia::class),
        ];

        $allPassed = true;
        foreach ($requirements as $requirement => $passed) {
            if ($passed) {
                $this->line("✅ {$requirement}");
            } else {
                $this->error("❌ {$requirement}");
                $allPassed = false;
            }
        }

        if (! $allPassed) {
            $this->error('❌ Some requirements are not met. Please install missing dependencies.');
            $this->line('Run: composer require spatie/laravel-translatable spatie/laravel-medialibrary');
        }

        return $allPassed;
    }

    protected function checkLaravelVersion(): bool
    {
        return version_compare(app()->version(), '11.0.0', '>=');
    }

    protected function checkLivewireVersion(): bool
    {
        if (! class_exists(\Livewire\Livewire::class)) {
            return false;
        }

        $version = \Livewire\Livewire::VERSION ?? '2.0.0';

        return version_compare($version, '3.0.0', '>=');
    }

    protected function publishAssets(): void
    {
        $this->info('📦 Publishing configuration and assets...');

        // Publish config
        $this->call('vendor:publish', [
            '--tag' => 'flux-cms-config',
            '--force' => $this->option('force'),
        ]);

        // Publish migrations
        $this->call('vendor:publish', [
            '--tag' => 'flux-cms-migrations',
            '--force' => $this->option('force'),
        ]);

        // Publish views
        $this->call('vendor:publish', [
            '--tag' => 'flux-cms-views',
            '--force' => $this->option('force'),
        ]);

        $this->line('✅ Assets published');
    }

    protected function runMigrations(): void
    {
        $this->info('🗃️ Running migrations...');

        $this->call('migrate');

        $this->line('✅ Migrations completed');
    }

    protected function createStorageLink(): void
    {
        if (! File::exists(public_path('storage'))) {
            $this->info('🔗 Creating storage link...');
            $this->call('storage:link');
            $this->line('✅ Storage link created');
        }
    }

    protected function createSampleContent(): void
    {
        if ($this->confirm('Would you like to create sample content?', true)) {
            $this->info('📝 Creating sample content...');

            // Run CMS content seeder
            $this->call('db:seed', ['--class' => 'FluxCms\\Core\\Database\\Seeders\\CmsContentSeeder']);

            $this->line('✅ Sample content created');
        }
    }

    protected function setPermissions(): void
    {
        if ($this->confirm('Would you like to create CMS permissions?', true)) {
            $this->info('🔐 Setting up permissions...');

            // Check if Spatie Permission is available
            if (class_exists(\Spatie\Permission\Models\Permission::class)) {
                $this->createCmsPermissions();
                $this->line('✅ Permissions created');
            } else {
                $this->warn('⚠️ Spatie Permission package not found. Skipping permission setup.');
                $this->line('Install with: composer require spatie/laravel-permission');
            }
        }
    }

    protected function createCmsPermissions(): void
    {
        // Run CMS permission seeder
        $this->call('db:seed', ['--class' => 'FluxCms\\Core\\Database\\Seeders\\CmsPermissionSeeder']);
    }

    protected function showNextSteps(): void
    {
        $this->newLine();
        $this->info('🎉 Next steps:');
        $this->line('1. Assign the "flux-cms" role to users who should access the CMS');
        $this->line('2. Create your first page: php artisan flux-cms:make:page');
        $this->line('3. Create custom components: php artisan flux-cms:make:component');
        $this->line('4. Visit /admin/cms to start editing');
        $this->newLine();
        $this->info('📚 Documentation: https://flux-cms.com/docs');
        $this->info('💬 Support: https://github.com/flux-cms/flux-cms/discussions');
    }
}
