<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Support\Facades\DB;

class AssignPermissions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'permissions:assign-all {role=super_admin}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Assign all permissions to a role';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $roleName = $this->argument('role');
        
        $role = Role::where('name', $roleName)->first();
        
        if (!$role) {
            $this->error("Role '{$roleName}' not found!");
            return 1;
        }
        
        $permissions = Permission::all();
        
        $this->info("Found {$permissions->count()} permissions");
        $this->info("Assigning to role: {$role->display_name}");
        
        $assigned = 0;
        foreach ($permissions as $permission) {
            $exists = DB::table('role_permissions')
                ->where('role_id', $role->id)
                ->where('permission_id', $permission->id)
                ->exists();
                
            if (!$exists) {
                DB::table('role_permissions')->insert([
                    'role_id' => $role->id,
                    'permission_id' => $permission->id,
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                $assigned++;
            }
        }
        
        $total = DB::table('role_permissions')->where('role_id', $role->id)->count();
        
        $this->info("Assigned {$assigned} new permissions");
        $this->info("Role now has {$total} total permissions");
        
        // Check for users.view specifically
        $usersView = DB::table('role_permissions')
            ->join('permissions', 'role_permissions.permission_id', '=', 'permissions.id')
            ->where('role_permissions.role_id', $role->id)
            ->where('permissions.name', 'users.view')
            ->exists();
            
        $this->info("users.view permission: " . ($usersView ? "✓ ASSIGNED" : "✗ MISSING"));
        
        return 0;
    }
}
