<?php
/**
 * List config files under storage/config.
 *
 * @package Flowaxy\Interface\CLI\Commands
 */

declare(strict_types=1);

namespace Flowaxy\Interface\CLI\Commands;

use Flowaxy\Core\System\PathResolver;
use Flowaxy\Interface\CLI\Command;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

use function is_dir;
use function str_replace;
use function trim;

final class ConfigListCommand extends Command
{
    public function getName(): string
    {
        return 'config:list';
    }

    public function getDescription(): string
    {
        return 'List config files in storage/config (optionally in a subfolder)';
    }

    public function getHelp(): string
    {
        return "Usage:\n"
            . "  php index.php config:list\n"
            . "  php index.php config:list system\n"
            . "  php index.php config:list plugins\n";
    }

    protected function handle(array $args): int
    {
        $base = PathResolver::storageConfig();
        $sub = $args[0] ?? '';
        $sub = trim((string) $sub);

        $dir = $sub !== '' ? $base . DS . $sub : $base;
        if (!is_dir($dir)) {
            $this->error("Config directory not found: {$dir}");
            return 1;
        }

        $this->output('Config files:');
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS));
        foreach ($it as $file) {
            if ($file->isFile() && $file->getExtension() === 'ini') {
                $path = (string) $file->getPathname();
                $rel = str_replace($base . DS, '', $path);
                $this->output('  - ' . $rel);
            }
        }

        return 0;
    }
}
