<?php
/// file: migrate.php

declare(strict_types=1);

$basePath = __DIR__;
if (is_file($basePath . '/vendor/autoload.php')) {
    require $basePath . '/vendor/autoload.php';
} else {
    spl_autoload_register(static function (string $class) use ($basePath): void {
        $prefix = 'App\\';
        if (! str_starts_with($class, $prefix)) {
            return;
        }
        $relative = str_replace('\\', '/', substr($class, strlen($prefix)));
        $file = $basePath . '/app/' . $relative . '.php';
        if (is_file($file)) {
            require $file;
        }
    });
}
require $basePath . '/app/Helpers/functions.php';

use App\Core\Database;
use App\Core\Env;
use App\Core\Config;

Env::load($basePath . '/.env');
Config::load($basePath . '/config');

$dbConfig = Config::get('database.connections.mysql', []);
if (! is_array($dbConfig) || ($dbConfig['database'] ?? '') === '') {
    fwrite(STDERR, "Set DB_NAME in .env\n");
    exit(1);
}

$pdo = Database::connect($dbConfig);

$pdo->exec('CREATE TABLE IF NOT EXISTS migrations (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  batch VARCHAR(32) NOT NULL,
  name VARCHAR(255) NOT NULL UNIQUE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');

$files = glob($basePath . '/database/migrations/*.php') ?: [];
sort($files);
$batch = date('YmdHis');

foreach ($files as $file) {
    $name = basename($file);
    $check = $pdo->prepare('SELECT id FROM migrations WHERE name = ?');
    $check->execute([$name]);
    if ($check->fetch()) {
        echo "Skip {$name}\n";
        continue;
    }
    /** @var callable $migration */
    $migration = require $file;
    if (! is_callable($migration)) {
        throw new RuntimeException("Invalid migration: {$name}");
    }
    $migration($pdo);
    $ins = $pdo->prepare('INSERT INTO migrations (batch, name) VALUES (?, ?)');
    $ins->execute([$batch, $name]);
    echo "Ran {$name}\n";
}

echo "Done.\n";
