-- Migration 0017: Unify instance IDs to INTEGER AUTOINCREMENT
-- Pre-launch clean slate: drop and recreate all instance + reaction tables

DROP TABLE IF EXISTS reactions;
DROP TABLE IF EXISTS projections;
DROP TABLE IF EXISTS event_refs;
DROP TABLE IF EXISTS events;
DROP TABLE IF EXISTS objects;

CREATE TABLE objects (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  type TEXT NOT NULL REFERENCES object_defs(name),
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);

CREATE TABLE events (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  type_hash TEXT NOT NULL REFERENCES event_def_versions(hash),
  payload TEXT NOT NULL,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);

CREATE TABLE event_refs (
  event_id INTEGER NOT NULL REFERENCES events(id),
  property TEXT NOT NULL,
  ref_id INTEGER NOT NULL REFERENCES objects(id),
  PRIMARY KEY (event_id, property)
);
CREATE INDEX idx_event_refs_obj ON event_refs(ref_id);

CREATE TABLE projections (
  def_hash TEXT NOT NULL REFERENCES projection_def_versions(hash),
  params_hash TEXT NOT NULL,
  params TEXT NOT NULL,
  value TEXT NOT NULL,
  last_event_id INTEGER NOT NULL DEFAULT 0,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
  PRIMARY KEY (def_hash, params_hash)
);

CREATE TABLE reactions (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  projection_def_hash TEXT NOT NULL REFERENCES projection_def_versions(hash),
  params_hash TEXT NOT NULL,
  params TEXT NOT NULL,
  action TEXT NOT NULL DEFAULT 'webhook',
  webhook_url TEXT,
  emit_event_type TEXT,
  emit_payload_template TEXT,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);
CREATE INDEX idx_reactions_projection ON reactions(projection_def_hash, params_hash);
