CREATE TABLE IF NOT EXISTS ivr_flows (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  flow_id TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL,
  description TEXT NOT NULL DEFAULT '',
  channel TEXT NOT NULL,
  queue_id TEXT NOT NULL,
  version INTEGER NOT NULL DEFAULT 1,
  is_active INTEGER NOT NULL DEFAULT 1,
  entry_node_id TEXT NOT NULL,
  flow_json TEXT NOT NULL,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS ix_ivr_flows_flow_id ON ivr_flows (flow_id);
CREATE INDEX IF NOT EXISTS ix_ivr_flows_name ON ivr_flows (name);
CREATE INDEX IF NOT EXISTS ix_ivr_flows_channel ON ivr_flows (channel);
CREATE INDEX IF NOT EXISTS ix_ivr_flows_queue_id ON ivr_flows (queue_id);
CREATE INDEX IF NOT EXISTS ix_ivr_flows_is_active ON ivr_flows (is_active);
CREATE INDEX IF NOT EXISTS ix_ivr_flows_created_at ON ivr_flows (created_at);
CREATE INDEX IF NOT EXISTS ix_ivr_flows_updated_at ON ivr_flows (updated_at);

CREATE TABLE IF NOT EXISTS ivr_sessions (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  session_id TEXT NOT NULL UNIQUE,
  call_id TEXT NOT NULL,
  interaction_id TEXT NULL,
  flow_id TEXT NOT NULL,
  queue_id TEXT NOT NULL,
  current_node_id TEXT NOT NULL,
  entered_digits_json TEXT NOT NULL DEFAULT '[]',
  status TEXT NOT NULL,
  outcome_code TEXT NULL,
  resolved_queue_id TEXT NULL,
  completed_at TEXT NULL,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS ix_ivr_sessions_session_id ON ivr_sessions (session_id);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_call_id ON ivr_sessions (call_id);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_interaction_id ON ivr_sessions (interaction_id);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_flow_id ON ivr_sessions (flow_id);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_queue_id ON ivr_sessions (queue_id);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_status ON ivr_sessions (status);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_outcome_code ON ivr_sessions (outcome_code);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_resolved_queue_id ON ivr_sessions (resolved_queue_id);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_completed_at ON ivr_sessions (completed_at);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_created_at ON ivr_sessions (created_at);
CREATE INDEX IF NOT EXISTS ix_ivr_sessions_updated_at ON ivr_sessions (updated_at);
