<?php

namespace kernel\services;

use Illuminate\Database\Migrations\DatabaseMigrationRepository;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Filesystem\Filesystem;
use kernel\App;
use kernel\helpers\Debug;

class MigrationService
{
    protected ModuleService $moduleService;

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

    /**
     * @throws \Exception
     */
    public function runAtPath(string $path = ROOT_DIR . '/migrations'): array
    {
        $path = getConst($path);
//        Debug::dd($path);

        try {
            $dmr = new DatabaseMigrationRepository(App::$db->capsule->getDatabaseManager(), 'migration');

            $m = new Migrator($dmr, App::$db->capsule->getDatabaseManager(), new Filesystem());

            return $m->run($path);
        } catch (\Exception $e) {
            throw new \Exception('Не удалось поднять миграции');
        }
    }

    public function rollbackAtPath(string $path): void
    {
        $path = getConst($path);
        try {
            $filesystem = new Filesystem();
            $dmr = new DatabaseMigrationRepository(App::$db->capsule->getDatabaseManager(), 'migration');

            $m = new Migrator($dmr, App::$db->capsule->getDatabaseManager(), $filesystem);

            $migrationFiles = $m->getMigrationFiles($path);
            foreach ($migrationFiles as $name => $migrationFile){
                $migrationInstance = $filesystem->getRequire($migrationFile);
                $migrationInstance->migration = $name;
                $migrationInstance->down();
                $dmr->delete($migrationInstance);
            }
        } catch (\Exception $e) {
            throw new \Exception('Не удалось откатить миграции');
        }
    }

}