<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Modules\Settings\Rbac\Repositories\PermissionRepository;
use App\Modules\Settings\Rbac\Services\TenantPermissionEvaluator;
use Illuminate\Console\Command;

class SyncTenantPermissionsCommand extends Command
{
    protected $signature = 'rbac:sync-permissions {--clear-cache : Clear per-user permission cache after sync}';

    protected $description = 'Sync permission rows from config/tenant-permissions.php (run after deploy)';

    public function handle(PermissionRepository $permissions): int
    {
        $slugs = config('tenant-permissions.abilities', []);
        if ($slugs === []) {
            $this->error('No abilities in config/tenant-permissions.php');

            return self::FAILURE;
        }

        $labels = [];
        foreach ($slugs as $slug) {
            $key = 'permissions.abilities.'.$slug;
            $labels[$slug] = __($key) !== $key ? __($key) : str_replace('.', ' ', (string) $slug);
        }

        $permissions->syncFromConfigList($labels);
        $this->info('Synced '.count($slugs).' permission slugs from config.');

        if ($this->option('clear-cache')) {
            $count = 0;
            User::query()->whereNotNull('tenant_id')->select('id')->chunkById(200, function ($users) use (&$count): void {
                foreach ($users as $user) {
                    TenantPermissionEvaluator::forgetCacheForUser($user);
                    $count++;
                }
            });
            $this->info("Cleared permission cache for {$count} tenant user(s).");
        }

        return self::SUCCESS;
    }
}
