<?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;
use DI\Definition\Exception\InvalidDefinition;
use Exception;

class callbacks
{
    //dynamic permissions. We need to loop over all known roles and create an "assign role" permission.
    public static function postAuth(): void
    {
        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();
            try {
                $roles = $roleEntity->loadMultiple();
            } catch (Exception) {
                $roles = [];
            }

            foreach ($roles as $role) {
                $permissions->registerPermission(
                    'AssignRole_'.$role->id,
                    'Assign Role: '.$role->name,
                    'Assign Roles'
                );
            }
        }
    }

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

                $notifier->send();
            } catch (InvalidDefinition $e) {
                logger('error')->error($e->getMessage());
            }
        }

        return $user;
    }
}
