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

use App\Database\Migration;

(static function (): void {
    $root = dirname(__DIR__);

    require $root . '/vendor/autoload.php';

    $dotenv = Dotenv\Dotenv::createImmutable($root);
    $dotenv->safeLoad();

    require $root . '/config/database.php';

    $migrationsDir = $root . '/database/migrations';
    $files = glob($migrationsDir . '/*.php');

    if ($files === false || $files === []) {
        echo "No migration files found.\n";
        exit(0);
    }

    sort($files);

    foreach ($files as $file) {
        $className = require $file;

        if (! class_exists($className)) {
            echo "Migration file {$file} did not define class {$className}\n";
            exit(1);
        }

        $migration = new $className();

        if (! $migration instanceof Migration) {
            echo "Class {$className} must extend " . Migration::class . "\n";
            exit(1);
        }

        echo "Running {$className}...\n";
        $migration->up();
    }

    echo "Done.\n";
})();
