<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;

/**
 * module:make
 *
 * Scaffolds a new ChargePanda module with the standard directory structure.
 *
 * Usage:
 *   php artisan module:make MyModule
 *   php artisan module:make MyModule --author="Your Name"
 *
 * After running, add "Modules\\": "modules/" to composer.json autoload.psr-4
 * (if not already present) and run: composer dump-autoload
 */
class ModuleMakeCommand extends Command
{
    protected $signature = 'module:make
        {name : PascalCase module name (e.g. Saas, Billing, Analytics)}
        {--author= : Author name to embed in module.json}
        {--description= : Short description to embed in module.json}';

    protected $description = 'Scaffold a new ChargePanda module';

    public function handle(): int
    {
        $name      = trim($this->argument('name'));
        $studly    = Str::studly($name);
        $slug      = Str::slug($name);
        $namespace = "Modules\\{$studly}";
        $base      = base_path("modules/{$studly}");

        if (is_dir($base)) {
            $this->error("Module directory already exists: modules/{$studly}");
            return self::FAILURE;
        }

        $this->info("Creating module: {$studly}");

        $this->makeDirectories($base);
        $this->writeModuleJson($base, $studly, $slug, $namespace);
        $this->writeServiceProvider($base, $studly, $slug, $namespace);
        $this->writeRoutesStub($base);
        $this->writeConfigStub($base, $slug);
        $this->writeMigrationPlaceholder($base);
        $this->writeViewsPlaceholder($base, $slug, $studly);

        $this->newLine();
        $this->line("  <fg=green>✓</> modules/{$studly}/module.json");
        $this->line("  <fg=green>✓</> modules/{$studly}/ModuleServiceProvider.php");
        $this->line("  <fg=green>✓</> modules/{$studly}/routes/web.php");
        $this->line("  <fg=green>✓</> modules/{$studly}/config/{$slug}.php");
        $this->line("  <fg=green>✓</> modules/{$studly}/resources/views/index.blade.php");

        $this->newLine();
        $this->comment('Next steps:');
        $this->line("  1. Add your routes to modules/{$studly}/routes/web.php");
        $this->line("  2. Check php artisan module:list to confirm the module is loaded");
        $this->newLine();
        $this->line("  <fg=gray>Tip: Run composer dump-autoload so your IDE can resolve module classes.</>");
        $this->line("  <fg=gray>     This is optional — ChargePanda's runtime autoloader handles class</>");
        $this->line("  <fg=gray>     resolution automatically without it.</>");

        return self::SUCCESS;
    }

    // -------------------------------------------------------------------------

    private function makeDirectories(string $base): void
    {
        $dirs = [
            $base,
            "{$base}/config",
            "{$base}/database/migrations",
            "{$base}/database/seeders",
            "{$base}/Http/Controllers",
            "{$base}/Models",
            "{$base}/resources/views",
            "{$base}/routes",
        ];

        foreach ($dirs as $dir) {
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
        }
    }

    private function writeModuleJson(string $base, string $studly, string $slug, string $namespace): void
    {
        $author      = $this->option('author')      ?? 'Unknown';
        $description = $this->option('description') ?? '';

        $data = [
            'name'        => $studly,
            'slug'        => $slug,
            'description' => $description,
            'version'     => '1.0.0',
            'author'      => $author,
            'provider'    => "{$namespace}\\ModuleServiceProvider",
            'enabled'     => true,
            'requires'    => [],
        ];

        file_put_contents(
            "{$base}/module.json",
            json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"
        );
    }

    private function writeServiceProvider(string $base, string $studly, string $slug, string $namespace): void
    {
        $stub = <<<PHP
<?php

namespace {$namespace};

use App\Support\AbstractModuleServiceProvider;

class ModuleServiceProvider extends AbstractModuleServiceProvider
{
    protected function modulePath(): string
    {
        return __DIR__;
    }

    protected function moduleNamespace(): string
    {
        return '{$namespace}';
    }

    public function register(): void
    {
        \$this->loadModuleConfig();
    }

    public function boot(): void
    {
        \$this->loadMigrations();
        \$this->loadViews();
        \$this->loadWebRoutes(['prefix' => '{$slug}']);
        \$this->loadCommands();
    }
}
PHP;

        file_put_contents("{$base}/ModuleServiceProvider.php", $stub . "\n");
    }

    private function writeRoutesStub(string $base): void
    {
        $stub = <<<PHP
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Module Web Routes
|--------------------------------------------------------------------------
|
| Routes registered here are wrapped in the "web" middleware group
| automatically by AbstractModuleServiceProvider::loadWebRoutes().
|
*/

Route::get('/', function () {
    return view('MODULE_SLUG::index');
});
PHP;

        file_put_contents("{$base}/routes/web.php", $stub . "\n");
    }

    private function writeConfigStub(string $base, string $slug): void
    {
        $stub = <<<PHP
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Module configuration
    |--------------------------------------------------------------------------
    |
    | Values here are merged under the "{$slug}" config key and can be
    | overridden by publishing this file or via environment variables.
    |
    */
];
PHP;

        file_put_contents("{$base}/config/{$slug}.php", $stub . "\n");
    }

    private function writeMigrationPlaceholder(string $base): void
    {
        file_put_contents("{$base}/database/migrations/.gitkeep", '');
        file_put_contents("{$base}/database/seeders/.gitkeep", '');
    }

    private function writeViewsPlaceholder(string $base, string $slug, string $studly): void
    {
        $stub = <<<BLADE
{{-- {$studly} module: index view --}}
<p>{$studly} module is working.</p>
BLADE;

        file_put_contents("{$base}/resources/views/index.blade.php", $stub . "\n");
    }
}
