<?php

declare(strict_types=1);

namespace Maestro\Core\Console\Commands;

use Illuminate\Console\Command;
use Maestro\Core\Services\MaestroLinkService;

class MaestroUnlinkCommand extends Command
{
    protected $signature = 'maestro:unlink';

    protected $description = 'Restore maestro/core and @maestro/core from registry lockfiles';

    public function handle(MaestroLinkService $linker): int
    {
        if (! $linker->isLinked()) {
            $this->comment('Maestro is not linked — nothing to do.');

            return self::SUCCESS;
        }

        if (! $this->confirm('Restore registry versions of maestro/core and @maestro/core?')) {
            return self::SUCCESS;
        }

        try {
            $linker->unlink(function (string $buffer): void {
                $this->output->write($buffer);
            });
        } catch (\Throwable $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        $this->newLine();
        $this->info('Maestro CORE unlinked — registry install restored.');
        $this->line('  • rm -rf node_modules/.vite');
        $this->line('  • Restart your dev server');

        return self::SUCCESS;
    }
}
