<?php

namespace apexl\Io\modules\install;

use apexl\Config\ConfigurationInterface;
use apexl\Io\enums\HttpMethod;
use apexl\Io\includes\Module;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\install\controllers\InstallModuleController;
use apexl\Io\modules\system\interfaces\ModuleFinderInterface;
use apexl\Io\modules\system\interfaces\ProvidesRoutesInterface;
use apexl\Io\services\HttpPaths;
use apexl\Io\services\InstallChecker;
use apexl\Vault\Vault;

/**
 * Base module file, provides required methods to register things like routes and middleware.
 * Class installModule
 * @package apexl\Io\modules\install
 */
class installModule extends Module implements ProvidesRoutesInterface
{
    public function __construct(
        private readonly HttpPaths $httpPaths,
        private readonly ModuleFinderInterface $moduleFinder,
        private readonly Vault $db,
        InstallChecker $installChecker,
        ConfigurationInterface $config,
    ) {
        parent::__construct($installChecker, $config);
    }

    public function initialise(): void
    {
        parent::initialise();
        $this->setBaseRoute(sprintf('/%s', ltrim($this->config->get('install.path'), '/')));
    }

    public function routes(RouteManager $routeManager): void
    {
        //@route /install/modules
        $this->addRoute($routeManager, HttpMethod::POST, 'install.modules', 'modules', InstallModuleController::class);
    }

    public function install(): void
    {
        //assume that our tables now exist, so lets set some defaults, including populating the modules table.
        //first, get all known modules, these should have been loaded already prior to this point.
        $availableModules = $this->moduleFinder->all();
        foreach ($availableModules as $module) {
            $this->db->insert('modules')->fields(['module' => $module])->execute();
        }

        //next we need to setup a site record. If nothing is defined in config, attempt to take it from the server instead.

        $this->db->insert('sites')->fields([
            'name' => 'core',
            'domain' => $this->httpPaths->frontendUrl(),
            'dbname' => $this->db->getDatabase()
        ])->execute();
    }
}
