<?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 seed 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);
    }
}

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

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

foreach ($seeds as $seedFile) {
    echo "Applying seed: " . basename($seedFile) . "\n";
    runSqlFile($seedFile);
}

echo "Seed data applied successfully.\n";
