<?php

namespace App\Console\Commands;

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

class ModuleMakeCommand extends Command
{
    protected $signature = 'module:make {name}';
    protected $description = 'Create a new module with standard directory structure';

    public function handle()
    {
        $name = $this->argument('name');
        $studlyName = Str::studly($name);
        $slug = Str::slug($name);
        $modulePath = app_path("Modules/{$studlyName}");

        if (File::exists($modulePath)) {
            $this->fail("Module '{$studlyName}' already exists at {$modulePath}");
        }

        $this->createDirectoryStructure($modulePath, $studlyName, $slug);
        $this->createModuleJson($modulePath, $studlyName, $slug);
        $this->createServiceProvider($modulePath, $studlyName, $slug);
        $this->createRoutes($modulePath, $slug);
        $this->createConfig($modulePath, $studlyName, $slug);

        $this->info("Module '{$studlyName}' created successfully!");
        $this->line("");
        $this->info("  Location:  app/Modules/{$studlyName}/");
        $this->info("  Provider:  App\\Modules\\{$studlyName}\\Providers\\{$studlyName}ServiceProvider");
        $this->line("");
        $this->info("Next steps:");
        $this->info("  1. Register the provider in app/Modules/{$studlyName}/module.json");
        $this->info("  2. Add module slug to your license's enabled_modules");
        $this->info("  3. Add routes to app/Modules/{$studlyName}/Routes/web.php");
        $this->info("  4. Run: composer dump-autoload");

        return 0;
    }

    protected function createDirectoryStructure(string $path, string $studlyName, string $slug): void
    {
        $directories = [
            'Config',
            'Database/Migrations',
            'Database/Seeders',
            'Http/Controllers',
            'Http/Requests',
            'Models',
            'Providers',
            'Routes',
            'Services',
            'Views',
        ];

        foreach ($directories as $dir) {
            File::makeDirectory("{$path}/{$dir}", 0755, true);
        }
    }

    protected function createModuleJson(string $path, string $studlyName, string $slug): void
    {
        $content = json_encode([
            'name' => $studlyName,
            'slug' => $slug,
            'version' => '1.0.0',
            'description' => "{$studlyName} module",
            'priority' => 100,
            'requires' => [],
            'providers' => [
                "App\\Modules\\{$studlyName}\\Providers\\{$studlyName}ServiceProvider",
            ],
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

        File::put("{$path}/module.json", $content);
    }

    protected function createServiceProvider(string $path, string $studlyName, string $slug): void
    {
        $content = <<<PHP
<?php

namespace App\\Modules\\{$studlyName}\\Providers;

use App\\Core\\Modules\\ModuleServiceProvider;

class {$studlyName}ServiceProvider extends ModuleServiceProvider
{
    protected string \$moduleName = '{$studlyName}';
    protected string \$moduleSlug = '{$slug}';
    protected string \$modulePath;

    public function __construct(\$app)
    {
        parent::__construct(\$app);
        \$this->modulePath = __DIR__ . '/..';
    }
}
PHP;

        File::put("{$path}/Providers/{$studlyName}ServiceProvider.php", $content);
    }

    protected function createRoutes(string $path, string $slug): void
    {
        $content = <<<PHP
<?php

use Illuminate\\Support\\Facades\\Route;

Route::middleware(['auth', 'module:{$slug}'])
    ->prefix('{$slug}')
    ->name('{$slug}.')
    ->group(function () {
        // Add {$slug} module routes here
    });
PHP;

        File::put("{$path}/Routes/web.php", $content);
    }

    protected function createConfig(string $path, string $studlyName, string $slug): void
    {
        $content = <<<PHP
<?php

return [
    'name' => '{$studlyName}',
    'slug' => '{$slug}',
];
PHP;

        File::put("{$path}/Config/{$slug}.php", $content);
    }
}
