<?php

namespace apexl\Io\modules\user\callbacks;

use apexl\Config\Singleton as ConfigSingleton;
use apexl\Io\includes\System;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\interfaces\newUserNotifier;
use apexl\Io\modules\user\services\Permissions;

class callbacks
{
    //dynamic permissions. We need to loop over all known roles and create an "assign role" permission.
    public static function postAuth()
    {
        if (!System::$installing) {
            $permissions = Permissions::getInstance();
            //dynamic permissions. We need to loop over all known roles and create an "assign role" permission.
            $roleEntity = new roleEntity();
            $roles = $roleEntity->loadMultiple();
            if ($roles !== []) {
                foreach ($roles as $role) {
                    $permissions->registerPermission(
                        'AssignRole_' . $role->id,
                        'Assign Role: ' . $role->name,
                        'Assign Roles'
                    );
                }
            }
        }
    }

    /** @noinspection PhpUnused */
    /**
     * @throws \Exception
     */
    public static function sendNewUserNotification(userEntity $user): userEntity
    {
        if (ConfigSingleton::getInstance()->user->sendNewUserNotification ?? false) {
            $notifier = System::makeRegisteredService(newUserNotifier::class, [
                'user' => $user,
            ]);

            $notifier->send();
        }

        return $user;
    }
}
