<?php

namespace apexl\Io\modules\install;

use apexl\Config\Singleton;
use apexl\Io\includes\Module;
use apexl\Io\includes\System;
use apexl\Io\modules\user\services\Permissions;
use apexl\Utils\Urls\Host;
use apexl\Io\modules\install\services\databaseTools;
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 {

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

    public function routes(){
        //we have no db data so lets assume we're installing.
        $installPath = System::getInstallPath();

        $this->route->get('/'.$installPath.'/list', installController::class.':list');
        //default install path - allows posting of data to the endpoint.
        //$this->route->post('/'.$installPath, installController::class.':install');
        $this->route->post('/'.$installPath.'/automatic', installController::class.':automatic', 'AllowAll');
        ///@todo module this into a "modules" module - amend schema
        $this->route->post('/'.$installPath.'/modules', installController::class.':installModule', 'AllowAll');
    }

    public function addServices(){
        return [
            databaseTools::class => function(){
                return new databaseTools();
            }
        ];
    }

    /**
     * Provide the install modules Schema.
     * @return mixed|void
     */
    public function schema(){
        return System::loadSchema(__DIR__.'/schema/schema.json');
    }

    public function install(){
        //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 = System::$module->getLoadedModules();
        $vault = Vault::getInstance();
        foreach($availableModules as $name => $namespace){
            $vault->insert('modules')->fields(['name' => $name, 'namespace' => $namespace])->execute();
        }

        //next we need to setup a site record. If nothing is defined in config, attempt to take it from the server instead.
        $config = Singleton::getInstance();

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