<?php

declare(strict_types=1);

namespace apexl\Io\modules\basicApi;

use apexl\Io\includes\Controller;
use apexl\Io\includes\Entity;
use apexl\Io\includes\moduleStore;
use apexl\Io\modules\user\classes\userManagedApiModule;
use apexl\Io\modules\user\enums\permissions\Common;
use apexl\Io\modules\user\interfaces\registersPermissions;
use apexl\Io\modules\user\services\Permissions;

/**
 * Base module file, provides required methods to register things like routes and middleware.
 * Class installModule
 * @package apexl\Io\modules\install
 */
class basicApiModule extends userManagedApiModule implements RegistersPermissions
{
    protected moduleStore $moduleStore;

    public function __construct(...$args)
    {
        parent::__construct();
        $this->moduleStore = moduleStore::getInstance();
        foreach (array_filter($args, fn(mixed $arg): bool => $arg instanceof Entity) as $arg) {
            $this->moduleStore->add($this->getName(), $arg);
        }
    }

    /**
     * @Todo - Clean up dynamic perms. For now uses core ENUMs as defaults for protection
     */
    public function routes(): void
    {
        if ($entities = $this->moduleStore->all($this->getName())) {
            foreach ($entities as $entity) {
                $this->addProtectedEntityRoutes($entity, [
                    'get' => [Controller::class.':get', Common::VIEW],
                    'put' => [Controller::class.':put', Common::UPDATE],
                    'post' => [Controller::class.':post', Common::CREATE],
                    'delete' => [Controller::class.':delete', Common::DELETE],
                ]);
            }
        }
    }

    public function permissions(Permissions $permissions): void
    {
        //Implement this in your main module file.
        //e.g. $permissions->registerPermission(Module::Permission, 'Module Permission', 'Module Permission Group');
    }
}
