<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;

final class DevMenuCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'menu';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Developer tools menu';

    public function handle(): int
    {
        if (! in_array(app()->environment(), ['local', 'testing'])) {
            $this->error('This command can only be run in local or testing environments.');

            return Command::FAILURE;
        }

        $this->info('');
        $this->info('  ╔═══════════════════════════════╗');
        $this->info('  ║     Go No Go — Dev Tools      ║');
        $this->info('  ╚═══════════════════════════════╝');
        $this->info('');

        $choice = $this->choice('Select an action', [
            0 => 'Exit',
            1 => 'Fresh migrate, seed & build',
        ]);

        if ($choice === 'Exit') {
            $this->info('Bye!');

            return Command::SUCCESS;
        }

        if ($choice === 'Fresh migrate, seed & build') {
            $this->freshMigrateAndBuild();
        }

        return Command::SUCCESS;
    }

    /**
     * Runs migrate:fresh with seeding, then runs npm build.
     *
     * Displays output from both processes and confirms success or failure.
     */
    private function freshMigrateAndBuild(): void
    {
        $this->info('');
        $this->comment('Running migrate:fresh --seed...');
        $this->call('migrate:fresh', ['--seed' => true]);

        $this->info('');
        $this->comment('Running npm run build...');

        $process = new Process(['npm', 'run', 'build']);
        $process->setWorkingDirectory(base_path());
        $process->setTimeout(120);
        $process->run(function (string $type, string $output): void {
            $this->output->write($output);
        });

        if ($process->isSuccessful()) {
            $this->info('');
            $this->info('Environment rebuilt successfully.');
        } else {
            $this->error('Build failed.');
        }
    }
}
