<?php

namespace App\Console\Commands;

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

class RanchInstallProductionCommand extends Command
{
    protected $signature = 'ranch:install-production
                            {--skip-seed : No ejecutar db:seed}';

    protected $description = 'Instalación post-despliegue: migrate, seed, storage:link y cachés';

    public function handle(): int
    {
        if (app()->environment('local') && ! $this->confirm('¿Ejecutar instalación de producción en entorno local?', false)) {
            return self::FAILURE;
        }

        $this->info('Migraciones...');
        Artisan::call('migrate', ['--force' => true]);
        $this->line(Artisan::output());

        if (! $this->option('skip-seed')) {
            $this->info('Seeders (roles, materiales, escenario engorda)...');
            Artisan::call('db:seed', ['--force' => true]);
            $this->line(Artisan::output());
        }

        $this->info('Enlace storage...');
        Artisan::call('storage:link');
        $this->line(Artisan::output());

        $this->info('Cachés de configuración...');
        Artisan::call('config:clear');
        Artisan::call('route:clear');
        Artisan::call('view:clear');
        Artisan::call('config:cache');
        Artisan::call('route:cache');
        Artisan::call('view:cache');

        if (class_exists(\Spatie\Permission\PermissionRegistrar::class)) {
            app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
        }

        $this->info('Instalación de producción completada.');

        return self::SUCCESS;
    }
}
