<?php

declare(strict_types=1);

namespace Apexl\Io\User\Hooks;

use Apexl\Io\Interfaces\AbstractHook;
use Apexl\Io\Module;
use Apexl\Io\Notifier\Exceptions\NotifierException;
use Apexl\Io\User\Interfaces\ProvidesPermissionsInterface;
use Apexl\Io\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')) {
            \Apexl\Io\Logger\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;
    }
}
