<?php
declare(strict_types=1);

use App\Core\Database\ConnectionFactory;
use App\Core\Database\Migrator;
use App\Core\Support\Env;

$basePath = dirname(__DIR__);
$vendorAutoload = $basePath . '/vendor/autoload.php';

if (is_file($vendorAutoload)) {
    require $vendorAutoload;
} else {
    spl_autoload_register(static function (string $class) use ($basePath): void {
        $prefix = 'App\\';
        if (!str_starts_with($class, $prefix)) {
            return;
        }

        $relative = substr($class, strlen($prefix));
        $file = $basePath . '/src/' . str_replace('\\', '/', $relative) . '.php';
        if (is_file($file)) {
            require $file;
        }
    });
}

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

/** @var array<string, mixed> $dbConfig */
$dbConfig = require $basePath . '/config/database.php';
$pdo = ConnectionFactory::make($dbConfig);
$migrator = new Migrator($pdo, $basePath . '/database/migrations');

try {
    $status = $migrator->status();
    echo 'Pending migrations: ' . (string) ($status['pending'] ?? 0) . PHP_EOL;

    $result = $migrator->runPending();
    foreach ((array) ($result['logs'] ?? []) as $line) {
        echo (string) $line . PHP_EOL;
    }

    echo 'Migrations complete.' . PHP_EOL;
} catch (Throwable $exception) {
    fwrite(STDERR, '[error] ' . $exception->getMessage() . PHP_EOL);
    exit(1);
}
