<?php

namespace App\Livewire\Concerns;

use App\Domain\Identity\Services\PermissionService;
use Illuminate\Database\Eloquent\Builder;

/**
 * Apply PermissionService::applyScope() to Livewire list queries.
 *
 * Usage in any list component:
 *   use AppliesRoleScope;
 *   protected string $scopePermission = 'participants.list';
 *
 * Then in render():
 *   $query = Participant::query();
 *   $this->applyRoleScope($query);
 */
trait AppliesRoleScope
{
    protected function applyRoleScope(Builder $query, ?string $permission = null): Builder
    {
        $user = auth()->user();

        if (!$user) {
            return $query->whereRaw('1 = 0');
        }

        if ($user->is_super_admin) {
            return $query;
        }

        $perm = $permission ?? $this->scopePermission ?? null;

        if (!$perm) {
            return $query;
        }

        return app(PermissionService::class)->applyScope($query, $user, $perm);
    }
}
