<?php
$host = getenv('DB_HOST') ?: 'db';
$user = getenv('DB_USER') ?: 'webgis';
$pass = getenv('DB_PASSWORD') ?: 'webgis_password';
$name = getenv('DB_NAME') ?: 'webgis_project';
$schema = __DIR__ . '/schema.sql';

if (!is_file($schema)) {
    fwrite(STDERR, "Schema file not found: $schema\n");
    exit(1);
}

$conn = null;
for ($i = 1; $i <= 30; $i++) {
    mysqli_report(MYSQLI_REPORT_OFF);
    $conn = @new mysqli($host, $user, $pass, $name);
    if (!$conn->connect_error) {
        break;
    }
    fwrite(STDERR, "Waiting for database ($i/30): {$conn->connect_error}\n");
    sleep(2);
}

if (!$conn || $conn->connect_error) {
    fwrite(STDERR, "Database connection failed.\n");
    exit(1);
}

$conn->set_charset('utf8mb4');
$sql = file_get_contents($schema);

if (!$conn->multi_query($sql)) {
    fwrite(STDERR, "Migration failed: {$conn->error}\n");
    exit(1);
}

do {
    if ($result = $conn->store_result()) {
        $result->free();
    }
    if ($conn->more_results() && !$conn->next_result()) {
        fwrite(STDERR, "Migration failed: {$conn->error}\n");
        exit(1);
    }
} while ($conn->more_results());

echo "Database migration completed.\n";
