<?php

namespace apexl\Io\modules\install;

use apexl\Io\enums\HttpMethod;
use apexl\Io\includes\Module;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\install\controllers\automaticController;
use apexl\Io\modules\install\controllers\installModuleController;
use apexl\Io\modules\install\controllers\listController;
use apexl\Io\modules\system\interfaces\ProvidesRoutesInterface;
use apexl\Io\modules\system\services\ModuleFinder;
use apexl\Io\services\InstallChecker;
use apexl\Utils\Urls\Host;
use apexl\Vault\Vault;
use function apexl\Io\config;

/**
 * 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 ModuleFinder $moduleFinder,
        private readonly Vault $db,
        InstallChecker $installChecker
    ) {
        parent::__construct($installChecker);
    }

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

    public function routes(RouteManager $routeManager): void
    {
        //@route /install/list
        $this->addRoute($routeManager, HttpMethod::GET, 'install.list', 'list', listController::class);
        //@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.

        $domain = config('app.site.backend_domain', Host::getHost());
        $this->db->insert('sites')->fields(['name' => 'core', 'domain' => $domain, 'dbname' => $this->db->getDatabase()]
        )->execute();
    }
}
