// engine/db/migrations/001-init.js — first migration.
//
// Creates the `events` table: a single append-only event stream that
// engine writers emit into and the dashboard's status cache reads
// `MAX(id)` from for cross-process cache invalidation. Replaces the
// mtime-tracker registry over the next few releases.
//
// Topic conventions (free-form text, but document the canonical list
// here so future contributors don't fragment):
//   - 'cache-invalidate'  — explicit dashboard.invalidateStatusCache() call
//   - 'dispatch'          — engine/dispatch.json mutation (mutateDispatch)
//   - 'work_items'        — engine/work-items.json or per-project file mutation
//   - 'pull_requests'     — engine/pull-requests.json or per-project file mutation
//   - 'prd'               — prd/*.json mutation
//   - 'watches'           — watches.json mutation
//   - 'config'            — config.json mutation
//
// Payload is optional JSON sidecar — currently unused by the dashboard
// cache check (single MAX(id) is sufficient) but useful for future
// debug tooling and topic-scoped subscribers.

module.exports = {
  version: 1,
  description: 'init: events table + topic/ts indices',
  up(db) {
    db.exec(`
      CREATE TABLE events (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        ts INTEGER NOT NULL DEFAULT (CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)),
        topic TEXT NOT NULL,
        payload TEXT
      );
      CREATE INDEX idx_events_topic_id ON events(topic, id DESC);
      CREATE INDEX idx_events_ts ON events(ts DESC);
    `);
  },
};
