"use strict";
/**
 * Shared SyncState singleton initializer.
 *
 * Used by both the Crawler and NightgateIndexerService to ensure the
 * SyncState row exists before any reads/writes.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureSyncStateSingleton = ensureSyncStateSingleton;
const cds_1 = __importDefault(require("@sap/cds"));
const { SELECT, INSERT } = cds_1.default.ql;
const midnight_1 = require("#cds-models/midnight");
const nightgate_config_1 = require("./nightgate-config");
async function ensureSyncStateSingleton(db, nodeUrl) {
    const existing = await db.run(SELECT.one.from(midnight_1.SyncState).where({ ID: 'SINGLETON' }));
    if (!existing) {
        try {
            const nightgateConfig = (0, nightgate_config_1.getNightgatePluginConfig)();
            const { network } = (0, nightgate_config_1.resolveNightgateRuntimeConfig)(nightgateConfig);
            const configuredNodeUrl = (0, nightgate_config_1.getConfiguredNightgateNodeUrl)(nightgateConfig);
            await db.run(INSERT.into(midnight_1.SyncState).entries({
                ID: 'SINGLETON',
                networkId: network,
                lastIndexedHeight: 0,
                syncStatus: 'stopped',
                nodeUrl: nodeUrl || configuredNodeUrl || '',
                chainHeight: 0,
                consecutiveErrors: 0
            }));
        }
        catch (err) {
            // Race condition: another service instance inserted first, safe to ignore
            if (!err.message?.includes('UNIQUE constraint'))
                throw err;
        }
    }
}
