<?php

declare(strict_types=1);

namespace apexl\Io\modules\BasicApi;

use apexl\Config\ConfigurationInterface;
use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\BasicApi\Services\BasicModuleEntityStore;
use apexl\Io\modules\system\interfaces\ProvidesRoutesInterface;
use apexl\Io\modules\user\classes\userManagedApiModule;
use apexl\Io\modules\user\enums\permissions\Common;
use apexl\Io\modules\user\interfaces\ProvidesPermissionsInterface;
use apexl\Io\modules\user\services\Permissions;
use apexl\Io\services\InstallChecker;

/**
 * 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 ProvidesPermissionsInterface, ProvidesRoutesInterface
{
    public function __construct(
        protected BasicModuleEntityStore $moduleStore,
        ConfigurationInterface $config,
        InstallChecker $installChecker,
    ) {
        parent::__construct($installChecker, $config);
    }

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

    protected function moduleStoreKey(): string
    {
        return $this::class;
    }

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