<?php

namespace App\Console\Commands;

use App\Models\Module;
use App\Services\System\ModuleLoader;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;

/**
 * modules:link
 *
 * Creates public symlinks for all installed modules that have a public/ directory.
 * Equivalent to `php artisan storage:link` but for modules.
 *
 * Usage:
 *   php artisan modules:link
 */
class ModuleLinkCommand extends Command
{
    protected $signature   = 'modules:link';
    protected $description = 'Create public symlinks for all installed module assets';

    public function handle(): int
    {
        if (! Schema::hasTable('modules')) {
            $this->error('Modules table not found. Run migrations first.');
            return self::FAILURE;
        }

        $modules = Module::all();

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

        $linked  = 0;
        $skipped = 0;

        foreach ($modules as $module) {
            $directory    = $this->getModuleDirectory($module);
            $modulePublic = base_path('modules/' . $directory . '/public');
            $link         = public_path('modules/' . $directory);

            if (! is_dir($modulePublic)) {
                $this->line("  <fg=gray>SKIP</>  {$module->name} — no public/ directory");
                $skipped++;
                continue;
            }

            if (is_link($link) || file_exists($link)) {
                $this->line("  <fg=gray>SKIP</>  {$module->name} — already linked");
                $skipped++;
                continue;
            }

            ModuleLoader::linkAssets($directory);
            $this->line("  <fg=green>LINK</>  {$module->name} → public/modules/{$directory}");
            $linked++;
        }

        $this->newLine();
        $this->info("Done. {$linked} linked, {$skipped} skipped.");

        return self::SUCCESS;
    }

    private function getModuleDirectory(Module $module): string
    {
        if (! empty($module->provider_class)) {
            $parts = explode('\\', $module->provider_class);
            if (count($parts) >= 2 && $parts[0] === 'Modules') {
                return $parts[1];
            }
        }

        return \Illuminate\Support\Str::studly($module->slug);
    }
}
