<?php

namespace apexl\Io\modules\install;

use apexl\Config\Singleton;
use apexl\Io\includes\Module;
use apexl\Io\includes\System;
use apexl\Io\interfaces\HasServicesInterface;
use apexl\Io\modules\install\services\Install;
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 implements HasServicesInterface
{
    public function __construct()
    {
        parent::__construct();
        $this->setBaseRoute('/'.ltrim(System::getInstallPath(), '/'));
    }

    //override core install check.
    public function isInstalled($forceRefresh = false)
    {
        $this->isInstalled = true;
        return $this->isInstalled;
    }

    public function routes()
    {
        //@route /install/list
        $this->addRoute('GET', 'install.list', 'list', installController::class.':list');
        //@route /install/automatic
        $this->addRoute('POST', 'install.automatic', 'automatic', installController::class.':automatic');
        //@route /install/modules
        $this->addRoute('POST', 'install.modules', 'modules', installController::class.':installModule');
    }

    public function addServices(): array
    {
        return [
            databaseTools::class => function () {
                return new databaseTools();
            },
            Install::class => function () {
                return new Install(Vault::getInstance());
            }
        ];
    }

    /**
     * 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();

        //install some core modules
    }
}
