-- Drop all v1 tables
DROP TABLE IF EXISTS subscriptions;
DROP TABLE IF EXISTS events;
DROP TABLE IF EXISTS edges;
DROP TABLE IF EXISTS objects;
DROP TABLE IF EXISTS relation_types;
DROP TABLE IF EXISTS object_types;

-- v2 Schema

CREATE TABLE types (
  name TEXT PRIMARY KEY,
  kind TEXT NOT NULL CHECK(kind IN ('obj', 'evt')),
  label TEXT NOT NULL
);

CREATE TABLE relation_types (
  name TEXT PRIMARY KEY,
  from_kind TEXT NOT NULL CHECK(from_kind IN ('obj', 'evt')),
  to_kind TEXT NOT NULL CHECK(to_kind IN ('obj', 'evt')),
  inverse TEXT NOT NULL,
  UNIQUE(inverse)
);

CREATE TABLE nodes (
  oid TEXT PRIMARY KEY,
  type TEXT NOT NULL REFERENCES types(name),
  data TEXT,
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
);
CREATE INDEX idx_nodes_type ON nodes(type);
CREATE INDEX idx_nodes_created ON nodes(created_at);

CREATE TABLE edges (
  oid TEXT PRIMARY KEY,
  from_oid TEXT NOT NULL REFERENCES nodes(oid),
  rel TEXT NOT NULL REFERENCES relation_types(name),
  to_oid TEXT NOT NULL REFERENCES nodes(oid),
  created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
  UNIQUE(from_oid, rel, to_oid)
);
CREATE INDEX idx_edges_from ON edges(from_oid);
CREATE INDEX idx_edges_to ON edges(to_oid);
CREATE INDEX idx_edges_rel ON edges(rel);
