<?php

namespace App\Console\Commands;

use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Console\Command;

class ChangeUserRole extends Command
{
    protected $signature = 'user:change-role
        {userId : The ID of the user}
        {role : The new role: user, admin, or moderator}';

    protected $description = 'Change a user role by user ID.';

    public function handle(): int
    {
        $role = UserRole::tryFrom((string) $this->argument('role'));

        if ($role === null) {
            $availableRoles = collect(UserRole::cases())
                ->map(fn (UserRole $role): string => $role->value)
                ->implode(', ');

            $this->error("Invalid role. Available roles: {$availableRoles}.");

            return self::FAILURE;
        }

        $user = User::query()->find((string) $this->argument('userId'));

        if ($user === null) {
            $this->error('User not found.');

            return self::FAILURE;
        }

        $user->forceFill([
            'role' => $role,
        ])->save();

        $this->info("User {$user->getKey()} role changed to {$role->value}.");

        return self::SUCCESS;
    }
}
