<?php

namespace apexl\Io\includes;

use apexl\Io\Client;
use apexl\ClassEngine\EngineSingleton;
use Phinx\Console\PhinxApplication;
use Phinx\Wrapper\TextWrapper;

/**
 * Relatively crude hook system, will need to be improved
 * Class Hook
 * @package apexl\Io\includes
 */
class Phinx extends EngineSingleton
{
    protected static ?TextWrapper $wrapper = null;
    protected static function connect(): void
    {
        //todo dont use this. Once new config class is in core we can fix.
        $client = Client::getInstance();
        $configDir = $client->getConfigDir();

        $app = new PhinxApplication();
        self::$wrapper = new TextWrapper($app);
        self::$wrapper->setOption('configuration', $configDir.'/phinx.php');
    }

    protected static function getModulePhinxMigrations($module): string
    {
        $reflection = new \ReflectionClass($module);
        //the updates folder is for specific migrations that should _not_ be included in the global phinx runs.
        return dirname($reflection->getFileName()) .'/db/updates';
    }

    public static function createUpdate(Module $module): void
    {
        if(self::$wrapper === null) {
            self::connect();
        }

        self::$wrapper->getMigrate(null, self::getModulePhinxMigrations($module));
    }

    public static function deleteDowngrade(Module $module): void
    {
        if(self::$wrapper === null) {
            self::connect();
        }

        self::$wrapper->getRollback(null, self::getModulePhinxMigrations($module));
    }

    public static function checkMigrationsAvailable(Module $module): void
    {
        if(self::$wrapper === null) {
            self::connect();
        }

        self::$wrapper->getStatus(null, self::getModulePhinxMigrations($module));
    }
}