<?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\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
{
    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);
        }
    }

    public function routes(): void
    {
        if ($entities = $this->moduleStore->all($this->getName())) {
            foreach ($entities as $entity) {
                $this->addProtectedEntityRoutes($entity, [
                    'get' => [Controller::class.':get', 'View'.$entity->getEntityName()],
                    'put' => [Controller::class.':put', 'Update'.$entity->getEntityName()],
                    'post' => [Controller::class.':post', 'Create'.$entity->getEntityName()],
                    'delete' => [Controller::class.':delete', 'Delete'.$entity->getEntityName()],
                ]);
            }
        }
    }

    public function registerPermissions(Permissions $permissions): void
    {
        if ($entities = $this->moduleStore->all($this->getName())) {
            foreach ($entities as $entity) {
                $permissions->registerPermission(
                    'View'.$entity->getEntityName(),
                    'View '.ucfirst($entity->getNiceName()),
                    ucfirst($this->getName())
                );
                $permissions->registerPermission(
                    'Update'.$entity->getEntityName(),
                    'Update '.ucfirst($entity->getNiceName()),
                    ucfirst($this->getName())
                );
                $permissions->registerPermission(
                    'Create'.$entity->getEntityName(),
                    'Create '.ucfirst($entity->getNiceName()),
                    ucfirst($this->getName())
                );
                $permissions->registerPermission(
                    'Delete'.$entity->getEntityName(),
                    'Delete '.ucfirst($entity->getNiceName()),
                    ucfirst($this->getName())
                );
            }
        }
    }
}
