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

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

$argv = $_SERVER['argv'] ?? [];
$command = $argv[1] ?? null;

$phinxBin = __DIR__ . '/../vendor/bin/phinx';
$phinxConfig = __DIR__ . '/../config/phinx.php';

$run = static function (string $phinxCommand) use ($phinxBin, $phinxConfig): never {
    $cmd = sprintf(
        '%s %s --configuration=%s',
        escapeshellarg($phinxBin),
        $phinxCommand,
        escapeshellarg($phinxConfig)
    );
    passthru($cmd, $exitCode);
    exit($exitCode);
};

switch ($command) {
    case 'db:migrate':
        $run('migrate');
        // no break
    case 'db:rollback':
        $run('rollback');
        // no break
    case 'db:seed':
        $run('seed:run');
        // no break

    case null:
    case '--help':
    case '-h':
        fwrite(STDOUT, <<<TXT
            Usage: console <command>

            Commands:
              db:migrate    Run Phinx migrations
              db:rollback   Roll back the most recent migration
              db:seed       Run all seeders idempotently

            TXT);
        exit(0);

    default:
        fwrite(STDERR, "Unknown command: {$command}\n");
        exit(1);
}
