<?php
declare(strict_types=1);

require dirname(__DIR__) . '/common.php';
require dirname(__DIR__) . '/db_init.php';

$path = dirname(__DIR__) . '/data/barometer_collection_import_bundle.json';
$bundle = json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);

[$pdo, $tmp, $lock] = qdb_open(true);
try {
    $pdo->exec('PRAGMA foreign_keys = OFF;');
    $result = qdb_import_questionnaires_bundle($pdo, $bundle, true);
    $pdo->exec('PRAGMA foreign_keys = ON;');
    qdb_save($tmp, $lock);
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (Throwable $e) {
    qdb_discard($tmp, $lock);
    fwrite(STDERR, 'ERROR: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
