-- Drop v2.0 tables
DROP TABLE IF EXISTS reactions;
DROP TABLE IF EXISTS projections;
DROP TABLE IF EXISTS reducers;
DROP TABLE IF EXISTS event_log;
DROP TABLE IF EXISTS edges;
DROP TABLE IF EXISTS nodes;
DROP TABLE IF EXISTS relation_types;
DROP TABLE IF EXISTS types;

-- v2.1 Schema

CREATE TABLE event_types (
  name TEXT PRIMARY KEY,
  label TEXT NOT NULL,
  schema TEXT NOT NULL
);

CREATE TABLE events (
  oid TEXT PRIMARY KEY,
  type TEXT NOT NULL REFERENCES event_types(name),
  payload TEXT NOT NULL,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);
CREATE INDEX idx_events_type ON events(type);
CREATE INDEX idx_events_created ON events(created_at);

CREATE TABLE event_refs (
  event_oid TEXT NOT NULL REFERENCES events(oid),
  property TEXT NOT NULL,
  ref_oid TEXT NOT NULL,
  PRIMARY KEY (event_oid, property)
);
CREATE INDEX idx_event_refs_obj ON event_refs(ref_oid);

CREATE TABLE reducers (
  name TEXT PRIMARY KEY,
  driven_by TEXT NOT NULL,
  params TEXT NOT NULL,
  filter TEXT NOT NULL,
  expression TEXT NOT NULL,
  initial_value TEXT
);

CREATE TABLE projections (
  reducer TEXT NOT NULL REFERENCES reducers(name),
  params TEXT NOT NULL,
  params_hash TEXT NOT NULL,
  value TEXT,
  updated_by TEXT,
  updated_at INTEGER,
  live INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (reducer, params_hash)
);

CREATE TABLE reactions (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  reducer TEXT NOT NULL,
  params_hash TEXT,
  condition TEXT,
  worker_url TEXT NOT NULL,
  config TEXT NOT NULL DEFAULT '{}',
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);
CREATE INDEX idx_reactions_reducer ON reactions(reducer);
