<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

use Crawl\Lib\Database;

function runSqlFile(string $filePath): void
{
    $sql = file_get_contents($filePath);
    if ($sql === false) {
        throw new RuntimeException("Unable to read migration file: {$filePath}");
    }

    $statements = preg_split('/;\s*(?=\n|$)/m', str_replace(["\r\n", "\r"], "\n", $sql));
    foreach ($statements as $statement) {
        $statement = trim($statement);
        if ($statement === '' || str_starts_with($statement, '--')) {
            continue;
        }
        Database::getInstance()->query($statement);
    }
}

$migrations = glob(__DIR__ . '/database/migrations/*.sql');
sort($migrations);

if (empty($migrations)) {
    echo "No migration files found.\n";
    exit(0);
}

foreach ($migrations as $migration) {
    echo "Applying migration: " . basename($migration) . "\n";
    runSqlFile($migration);
}

echo "Migrations applied successfully.\n";
