<?php

namespace App\Console\Commands;

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

class CheckAdminRole extends Command
{
    protected $signature = 'admin:check {email=admin@example.com}';
    protected $description = 'Check and assign Super Admin role to user';

    public function handle()
    {
        $email = $this->argument('email');
        
        // Check if user exists
        $user = User::where('email', $email)->first();
        
        if (!$user) {
            $this->error("User with email {$email} not found!");
            return Command::FAILURE;
        }
        
        $this->info("Found user: {$user->email}");
        $this->info("User ID: {$user->id}");
        
        // Check current roles
        $userRoles = $user->getRoleNames();
        $this->info("Current roles: " . $userRoles->implode(', '));
        
        // Check if Super Admin role exists
        $superAdminRole = Role::where('name', 'Super Admin')->first();
        
        if (!$superAdminRole) {
            $this->error("Super Admin role not found! Please run: php artisan db:seed --class=PermissionSeeder");
            return Command::FAILURE;
        }
        
        // Check if user already has Super Admin role
        if ($user->hasRole('Super Admin')) {
            $this->info("User already has Super Admin role!");
            
            // Check permissions
            $permissions = $user->getAllPermissions();
            $this->info("User has {$permissions->count()} permissions");
            
            if ($permissions->contains('name', 'View Users')) {
                $this->info("✅ User has 'View Users' permission");
            } else {
                $this->error("❌ User missing 'View Users' permission");
            }
            
            if ($permissions->contains('name', 'View Roles')) {
                $this->info("✅ User has 'View Roles' permission");
            } else {
                $this->error("❌ User missing 'View Roles' permission");
            }
            
        } else {
            // Assign Super Admin role
            $user->assignRole($superAdminRole);
            $this->info("✅ Super Admin role assigned successfully!");
        }
        
        return Command::SUCCESS;
    }
}