<?php

namespace App\Console\Commands;

use App\Support\ModuleLoader;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;

/**
 * module:list
 *
 * Lists all installed modules and their status.
 * Reads from the modules DB table when available; falls back to filesystem scan.
 *
 * Usage:
 *   php artisan module:list
 */
class ModuleListCommand extends Command
{
    protected $signature = 'module:list';

    protected $description = 'List all ChargePanda modules';

    public function handle(): int
    {
        // DB-based listing (post-install, source of truth)
        if (Schema::hasTable('modules')) {
            return $this->listFromDatabase();
        }

        // Filesystem fallback (fresh install, before migrations run)
        return $this->listFromFilesystem();
    }

    private function listFromDatabase(): int
    {
        $modules = \App\Models\Module::orderBy('name')->get();

        if ($modules->isEmpty()) {
            $this->info('No modules installed.');
            return self::SUCCESS;
        }

        $rows = $modules->map(fn($m) => [
            $m->slug,
            $m->name,
            $m->version,
            $m->status === 'active'
                ? '<fg=green>active</>'
                : '<fg=red>inactive</>',
            $m->installed_at?->format('Y-m-d') ?? '—',
        ]);

        $this->table(['Slug', 'Name', 'Version', 'Status', 'Installed'], $rows);

        return self::SUCCESS;
    }

    private function listFromFilesystem(): int
    {
        $modules = ModuleLoader::discover();

        if (empty($modules)) {
            $this->info('No modules found in /modules.');
            return self::SUCCESS;
        }

        $rows = [];

        foreach ($modules as $module) {
            $providerExists = isset($module['provider']) && class_exists($module['provider'])
                ? '<fg=green>✓</>'
                : '<fg=yellow>not loaded</>';

            $rows[] = [
                $module['slug']    ?? basename($module['path']),
                $module['name']    ?? '—',
                $module['version'] ?? '—',
                '<fg=yellow>not registered</>',
                $providerExists,
            ];
        }

        $this->table(['Slug', 'Name', 'Version', 'Status', 'Provider'], $rows);
        $this->warn('Note: modules table not found — run migrations to enable DB-based module management.');

        return self::SUCCESS;
    }
}
