<?php
namespace Misuzu\Console\Commands;

use Misuzu\DB;
use Misuzu\MisuzuContext;
use Misuzu\Console\CommandArgs;
use Misuzu\Console\CommandInterface;

class MigrateCommand implements CommandInterface {
    private MisuzuContext $context;

    public function __construct(MisuzuContext $ctx) {
        $this->context = $ctx;
    }

    public function getName(): string {
        return 'migrate';
    }
    public function getSummary(): string {
        return 'Runs database migrations.';
    }

    public function dispatch(CommandArgs $args): void {
        if($args->getArg(0) === 'rollback') {
            echo 'Migration rollback is gone.' . PHP_EOL;
            return;
        }

        try {
            touch(MSZ_ROOT . '/.migrating');
            chmod(MSZ_ROOT . '/.migrating', 0777);

            echo 'Creating migration manager...' . PHP_EOL;
            $manager = $this->context->createMigrationManager();

            echo 'Preparing to run migrations...' . PHP_EOL;
            $manager->init();

            echo 'Creating migration repository...' . PHP_EOL;
            $repo = $this->context->createMigrationRepo();

            echo 'Running migrations...' . PHP_EOL;
            $completed = $manager->processMigrations($repo);

            if(empty($completed)) {
                echo 'There were no migrations to run!' . PHP_EOL;
            } else {
                echo 'The following migrations have been completed:' . PHP_EOL;
                foreach($completed as $migration)
                    echo '  - ' . $migration . PHP_EOL;
            }

            echo PHP_EOL;
        } finally {
            unlink(MSZ_ROOT . '/.migrating');
        }
    }
}
