#!/usr/bin/env php
<?php

use Composer\Autoload\ClassLoader;
use Engelsystem\Application;
use Engelsystem\Database\Migration\Migrate;
use Engelsystem\Database\Migration\Direction;
use Engelsystem\Database\Migration\MigrationServiceProvider;
use Engelsystem\Environment;
use Engelsystem\Exceptions\Handler;
use Engelsystem\Exceptions\Handlers\NullHandler;

require_once __DIR__ . '/../includes/application.php';

/** @var $loader ClassLoader */
$baseDir = __DIR__ . '/../db/migrations';

/** @var Application $app */
$app = app();
$app->register(MigrationServiceProvider::class);

/** @var Handler $errorHandler */
$errorHandler = $app->get(Handler::class);
$errorHandler->setHandler(Environment::PRODUCTION, new NullHandler());

/** @var Migrate $migration */
$migration = $app->get('db.migration');
$migration->setOutput(function ($text) { echo $text . PHP_EOL; });

$script = array_shift($argv);
$argv = array_map('strtolower', $argv);
if (in_array('help', $argv) || in_array('--help', $argv) || in_array('-h', $argv)) {
    echo PHP_EOL . 'Usage: ' . $script . ' [up|down] [one-step] [force|-f]' . PHP_EOL . PHP_EOL;
    exit;
}

$direction = Direction::UP;
if (in_array('down', $argv)) {
    $argv = array_values($argv);
    $direction = Direction::DOWN;
}

$oneStep = false;
if (in_array('one-step', $argv)) {
    $oneStep = true;
}

$force = false;
if (in_array('force', $argv) || in_array('--force', $argv) || in_array('-f', $argv)) {
    $force = true;
}

$migration->run($baseDir, $direction, $oneStep, $force);
