-- Add handler_code column to reactions table
-- Pre-launch: drop and recreate
DROP TABLE IF EXISTS reaction_logs;
DROP TABLE IF EXISTS reactions;

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,
  handler_code TEXT,
  handler_timeout_ms INTEGER DEFAULT 5000,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);
CREATE INDEX idx_reactions_projection ON reactions(projection_def_hash, params_hash);

CREATE TABLE reaction_logs (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  reaction_id INTEGER NOT NULL,
  trigger_event_id INTEGER NOT NULL,
  projection_def TEXT NOT NULL,
  old_value TEXT,
  new_value TEXT,
  action TEXT NOT NULL,
  status TEXT NOT NULL,
  handler_output TEXT,
  duration_ms INTEGER,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);
CREATE INDEX idx_rlog_reaction ON reaction_logs(reaction_id);
CREATE INDEX idx_rlog_event ON reaction_logs(trigger_event_id);

CREATE TABLE IF NOT EXISTS reaction_kv (
  reaction_id INTEGER NOT NULL,
  key TEXT NOT NULL,
  value TEXT NOT NULL,
  PRIMARY KEY (reaction_id, key)
);
