// engine/db-events.js — `emitStateEvent(topic, payload?)` helper.
//
// Append a row to the `events` table so the dashboard's status cache (and
// any future topic-scoped subscriber) sees the change on its next poll.
// Designed for the engine-side mutator wrappers (mutateDispatch,
// mutateWorkItems, mutatePullRequests, …) to call after a successful
// write — the dashboard's getStatus polls MAX(events.id) as its single
// cache-version source of truth.
//
// Hard contract: this MUST be best-effort. Engine writers throwing from
// a cache-invalidation side effect would be a serious regression. Any
// SQLite failure (Node too old, DB locked, disk full) is swallowed.
// The mtime tracker remains as a fallback while we transition.

let _logged = false;

function emitStateEvent(topic, payload) {
  try {
    const { getDb } = require('./db');
    const db = getDb();
    if (payload !== undefined && payload !== null) {
      db.prepare('INSERT INTO events (topic, payload) VALUES (?, ?)')
        .run(String(topic), JSON.stringify(payload));
    } else {
      db.prepare('INSERT INTO events (topic) VALUES (?)').run(String(topic));
    }
  } catch (e) {
    // Log once per process so the operator notices a broken install
    // without spamming on every write.
    if (!_logged) {
      _logged = true;
      try {
        // eslint-disable-next-line no-console
        console.warn(`[db-events] state event emission disabled: ${e.message}`);
      } catch { /* console unavailable in some test seams */ }
    }
  }
}

module.exports = { emitStateEvent };
