<?php

namespace App\Console\Commands;

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

class MakeActionCommand extends Command
{
    protected $signature = 'make:action {name : The name of the action class (e.g. Home/HomePageAction)}';
    protected $description = 'Create a new HTTP Action class in app/Http/Actions';

    public function handle(): int
    {
        $name = Str::studly($this->argument('name'));
        $path = base_path('app/Http/Actions/' . str_replace('\\', '/', $name) . '.php');
        $namespace = 'App\\Http\\Actions\\' . Str::beforeLast(str_replace('/', '\\', $name), '\\');
        $className = Str::afterLast($name, '/');

        // If directory doesn't exist, create it
        File::ensureDirectoryExists(dirname($path));

        if (File::exists($path)) {
            $this->error('Action class already exists.');
            return static::FAILURE;
        }

        $stub = $this->getStub($namespace, $className);

        File::put($path, $stub);

        $this->info("Action class created: {$path}");
        return static::SUCCESS;
    }

    protected function getStub(string $namespace, string $class): string
    {
        return <<<PHP
<?php

namespace {$namespace};

use Illuminate\Http\Request;
use Illuminate\View\View;

class {$class}
{
    public function __invoke(Request \$request): View
    {
        return view('REPLACE_WITH_VIEW');
    }
}
PHP;
    }
}
