<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\hooks;

use apexl\Io\includes\Module;
use apexl\Io\interfaces\AbstractHook;
use apexl\Io\modules\notifier\exceptions\notifierException;
use apexl\Io\modules\user\interfaces\ProvidesPermissionsInterface;
use apexl\Io\modules\user\services\Permissions;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

final readonly class RegisterModulePermissions implements AbstractHook
{

    public function hooks(): array
    {
        return ['initialiseModule'];
    }

    /**
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws notifierException
     * @throws Exception
     */
    public function __invoke(Module $module, Permissions $permissions): Module
    {
        if (method_exists($module, 'registerPermissions')) {
            logger('error')->warning(
                sprintf(
                    'Deprecation - Module \'%s\' should register permissions by implementing %s\n',
                    $module->getName(),
                    ProvidesPermissionsInterface::class,
                ),
            );
            $module->registerPermissions($permissions);

            return $module;
        }

        if ($module instanceof ProvidesPermissionsInterface) {
            $module->permissions($permissions);
        }

        return $module;
    }
}
