<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class AssignAdminPermissions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:assign-permissions {user_id? : The ID of the admin user to assign permissions to}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Assign all permissions to an admin user';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Get user ID from argument or prompt
        $userId = $this->argument('user_id');

        if (!$userId) {
            // List all users
            $users = User::select('id', 'first_name', 'last_name', 'email')->get();

            if ($users->isEmpty()) {
                $this->error('❌ No users found in database!');
                return Command::FAILURE;
            }

            $this->info('Available users:');
            foreach ($users as $user) {
                $this->line("ID: {$user->id} - {$user->first_name} {$user->last_name} ({$user->email})");
            }

            $userId = $this->ask('Enter the user ID to assign permissions to:');
        }

        $user = User::find($userId);

        if (!$user) {
            $this->error("❌ User with ID {$userId} not found!");
            return Command::FAILURE;
        }

        // Get or create super_admin role
        $superAdminRole = Role::firstOrCreate(['name' => 'super_admin']);

        // Get all permissions
        $allPermissions = Permission::all();

        if ($allPermissions->isEmpty()) {
            $this->error('❌ No permissions found! Run migrations first.');
            return Command::FAILURE;
        }

        // Assign super_admin role and all permissions
        $user->assignRole($superAdminRole);
        $user->givePermissionTo($allPermissions);

        $this->info("✅ Successfully assigned super_admin role and all permissions to: {$user->email}");
        $this->info("Total permissions assigned: {$allPermissions->count()}");

        return Command::SUCCESS;
    }
}

