<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\hooks;

use apexl\Io\hooks\AbstractHook;
use apexl\Io\includes\System;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\services\Permissions;
use Exception;

/**
 * Dynamic permissions.
 * We need to loop over all known roles and create an "assign role" permission.
 */
final readonly class RegisterRolePermissions extends AbstractHook
{

    static protected function hooks(): array
    {
        return ['postAuth'];
    }

    /**
     * @throws Exception
     */
    public function __invoke(): void
    {
        if (!System::$installing) {
            $permissions = Permissions::getInstance();

            $roleEntity = new roleEntity();
            $roles = $roleEntity->loadMultiple();
            foreach ($roles as $role) {
                $permissions->registerPermission(
                    sprintf('AssignRole_%s', $role->id),
                    sprintf('Assign Role: %s', $role->name),
                    'Assign Roles'
                );
            }
        }
    }
}
