// engine/db/migrations/005-logs.js
//
// Phase 4: replace engine/log.json with a `logs` table.
//
// Logs are append-only with a 2500-entry ring buffer (the legacy JSON
// path trimmed to 2000 when length hit 2500). The table preserves that
// behaviour:
//   - Each log() emits one row via INSERT.
//   - After insert, a tail-trim DELETEs everything older than the most
//     recent N (default 2500, configurable via ENGINE_DEFAULTS.logCapEntries).
//
// Schema is intentionally narrow: an auto-incrementing id (preserves
// insertion order for the ring-buffer trim), the timestamp in ms (so the
// dashboard can do range queries without a TEXT parse), a level/message
// pair the dashboard already keys on, and a `meta` JSON blob for any
// extra fields the caller passed.
//
// No backfill — engine/log.json is ephemeral and the next tick will
// start populating SQL fresh. The legacy file stays on disk as a
// dual-write mirror (test fixtures + getEngineLog fallback) until
// Phase 4.5 migrates the readers.

module.exports = {
  version: 5,
  description: 'logs: append-only table for engine log entries',
  up(db) {
    db.exec(`
      CREATE TABLE logs (
        id        INTEGER PRIMARY KEY AUTOINCREMENT,
        ts_ms     INTEGER NOT NULL,
        level     TEXT NOT NULL,
        message   TEXT NOT NULL,
        meta      TEXT
      );
      CREATE INDEX idx_logs_ts        ON logs(ts_ms DESC);
      CREATE INDEX idx_logs_level_ts  ON logs(level, ts_ms DESC);
    `);
  },
};
