<?php

declare(strict_types=1);

namespace app\vendor\apexl\io\src\Io\modules\system\commands;

use apexl\Io\modules\system\services\modules;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'modules:list', description: 'List modules')]
class ModuleListCommand extends Command
{
    public function __construct(private readonly modules $modules, ?string $name = null)
    {
        parent::__construct($name);
    }

    protected function configure(): void
    {
        $this->addOption('installed', 'i', InputOption::VALUE_NONE, 'List only installed modules');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $installed = $input->getOption('installed');

        $installedModules = array_map(fn(object $module) => ltrim($module->namespace, '\\'),
            $this->modules->getActiveModules());
        $availableModules = array_values($this->modules->getModulesFromNamespace());

        $modules = $installed ? $installedModules : $availableModules;
        sort($modules);

        $io->table(
            ['Module', 'Installed'],
            array_map(
                function (string $module) use ($installedModules): array {
                    $installed = in_array($module, $installedModules);
                    $color = $installed ? 'info' : 'comment';

                    return [
                        sprintf('<%2$s>%1$s</%2$s>', $module, $color),
                        sprintf('<%2$s>%1$s</%2$s>', $installed ? 'TRUE' : 'FALSE', $color),
                    ];
                },
                $modules,
            ),
        );


//        var_dump($modules);


        return 0;
    }
}
