<?php

namespace App\Console\Commands;

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

class SyncUserPermissions extends Command
{
    protected $signature = 'permissions:sync-users';
    protected $description = 'Re-sync all user permissions and clear cache';

    public function handle()
    {
        $this->info('Clearing permission cache...');
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $this->info('Re-syncing user permissions...');
        $users = User::with('roles')->get();

        foreach ($users as $user) {
            if ($user->roles->count() > 0) {
                $user->syncRoles($user->roles);
                $this->info("Synced: {$user->name}");
            }
        }

        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $this->info('Done! All permissions synced.');
    }
}
