<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Domain\Plugin\PluginManager;
use Illuminate\Console\Command;

class PluginsSyncCommand extends Command
{
    protected $signature = 'plugins:sync {--enable= : Comma-separated plugin names to enable after sync}';

    protected $description = 'Discover plugins on disk and sync into the plugins table';

    public function handle(PluginManager $manager): int
    {
        $discovered = $manager->syncDiscoveredPlugins();
        $this->info('Synced '.$discovered->count().' plugins.');

        foreach ($discovered as $name => $manifest) {
            $this->line('- '.$name.' v'.($manifest['version'] ?? '1.0.0'));
        }

        $enable = trim((string) $this->option('enable'));
        if ($enable !== '') {
            foreach (array_filter(array_map('trim', explode(',', $enable))) as $name) {
                $manager->enable($name);
                $this->info("Enabled: {$name}");
            }
        }

        return self::SUCCESS;
    }
}
