<?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';
require_once dirname(__DIR__) . '/lib/response.php';
require_once dirname(__DIR__) . '/common.php';

qdb_env_override('QDB_DRIVER', 'mysql');
require_once dirname(__DIR__) . '/db_init.php';

[$pdo] = qdb_open(true);

foreach (['users', 'questionnaire', 'questionnaire_submission', 'system_setting'] as $table) {
    if (!qdb_table_exists($pdo, $table)) {
        throw new RuntimeException("MySQL smoke test: missing table {$table}");
    }
}

if (qdb_schema_version($pdo) !== QDB_VERSION) {
    throw new RuntimeException('MySQL smoke test: incorrect schema version');
}

// Schema application must be safe to retry after an interrupted or concurrent bootstrap.
qdb_exec_schema_file($pdo, qdb_schema_file());

$pdo->exec("DELETE FROM language WHERE languageCode = 'ci-smoke'");
$upsert = $pdo->prepare(
    'INSERT INTO language (languageCode, name, enabled) VALUES (:code, :name, 1) '
    . qdb_upsert_update(['languageCode'], ['name' => 'excluded.name'])
);
$upsert->execute([':code' => 'ci-smoke', ':name' => 'First']);
$upsert->execute([':code' => 'ci-smoke', ':name' => 'Updated']);
$name = $pdo->query("SELECT name FROM language WHERE languageCode = 'ci-smoke'")->fetchColumn();
if ($name !== 'Updated') {
    throw new RuntimeException('MySQL smoke test: upsert failed');
}
$pdo->exec("DELETE FROM language WHERE languageCode = 'ci-smoke'");

fwrite(STDOUT, "MySQL smoke test passed\n");
