<?php

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;
use apexl\Io\traits\hasEntityStore;

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

    public function __construct()
    {
        parent::__construct();

        $this->moduleStore = moduleStore::getInstance();
        $this->storeEntities(func_get_args());
    }

    public function routes()
    {
        $this->entitiesRoutes();
    }

    private function entityRoutes(Entity $entity): void
    {
        $this->addProtectedEntityRoutes($entity, $this->entityRoutesArray($entity));
    }

    private function entityRoutesArray(Entity $entity): array
    {
        return [
            'get' => $this->entityRoute($entity, 'get', 'View'),
            'put' => $this->entityRoute($entity, 'put', 'Update'),
            'post' => $this->entityRoute($entity, 'post', 'Create'),
            'delete' => $this->entityRoute($entity, 'delete', 'Delete'),
        ];
    }

    private function entityRoute(Entity $entity, string $method, ?string $prefix = null): array
    {
        $prefix = $prefix ?? ucfirst($method);

        return [
            sprintf('%s:%s', $this->controllerClass($entity), $method),
            sprintf('%s%s', $prefix, $entity->getEntityName()),
        ];
    }

    protected function controllerClass(Entity $entity): string
    {
        return Controller::class;
    }

    public function registerPermissions(Permissions $permissions)
    {
        if ($entities = $this->moduleStore::getModuleEntities($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())
                );
            }
        }
    }
}
