<?php


namespace kernel\console\controllers;


use Illuminate\Filesystem\Filesystem;
use kernel\App;
use kernel\console\CgMigrationCreator;
use kernel\console\ConsoleController;
use Illuminate\Database\Migrations\DatabaseMigrationRepository;
use Illuminate\Database\Migrations\MigrationCreator;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
use kernel\services\ModuleService;


class MigrationController extends ConsoleController
{
    protected ModuleService $moduleService;

    public function __construct()
    {
        parent::__construct();
        $this->moduleService = new ModuleService();
    }

    //create migrations table
    public function actionCreateMigrationTable(): void
    {
        try {
            App::$db->schema->create('migration', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('migration', 255);
                $table->integer('batch');
            });
            $this->out->r("Success", 'green');
        } catch (\Exception $e) {
            $this->out->r($e->getMessage(), 'red');
        }
    }

    // create migrations
    public function actionCreate(): void
    {
        try {
            if (!isset($this->argv['name'])) {
                throw new \Exception('Missing migration "--name" specified');
            }
            $m = new CgMigrationCreator(new Filesystem(), CgMigrationCreator::getCustomStubPath());

            $path = $this->argv['path'] ?? 'migrations';

            $res = $m->create(
                $this->argv['name'],
                ROOT_DIR . '/' . $path,
                $this->argv['table'] ?? null,
                !isset($this->argv['update'])
            );
            $this->out->r(basename($res) . " created", 'green');
        } catch (\Exception $e) {
            $this->out->r('Message: ' . $e->getMessage(), 'red');
        }
    }

    //execute migrations
    public function actionRun(): void
    {
        try {
            $dmr = new DatabaseMigrationRepository(App::$db->capsule->getDatabaseManager(), 'migration');

            $m = new Migrator($dmr, App::$db->capsule->getDatabaseManager(), new Filesystem());
            if (\kernel\App::$db->schema->hasTable('option')) {
                $migrationPaths = array_merge($this->moduleService->getModulesMigrationsPaths(), [ROOT_DIR . '/migrations']);
            } else {
                $migrationPaths = [ROOT_DIR . '/migrations'];
            }

            $res = $m->run($migrationPaths);
            foreach ($res as $re) {
                $this->out->r(basename($re), 'green');
            }
        } catch (\Exception $e) {
            $this->out->r('Message: ' . $e->getMessage(), 'red');
        }
    }

    public function actionRollback(): void
    {
        try {
            $step = $this->argv['step'] ?? 1;
            $dmr = new DatabaseMigrationRepository(App::$db->capsule->getDatabaseManager(), 'migration');

            $m = new Migrator($dmr, App::$db->capsule->getDatabaseManager(), new Filesystem());
            //$migrationPaths = array_merge(App::$migrationsPaths, [WORKSPACE_DIR . '/console/migrations']);
            $migrationPaths = [ROOT_DIR . '/migrations'];
            $res = $m->rollback($migrationPaths, ['step' => $step]);
            print_r($step);
            foreach ($res as $re) {
                $this->out->r(basename($re), 'green');
            }
        } catch (\Exception $e) {
            $this->out->r('Message: ' . $e->getMessage(), 'red');
        }
    }
}