-- Story flow graph (Phase 1: authoring only). A mystery is a directed graph of
-- nodes; each node has N output terminals, and a terminal carries its own single
-- outgoing wire (to_node_id) — there is no separate edges table. The runtime is
-- untouched in this phase; it still plays via the slot model.

CREATE TABLE osint.story_nodes (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  mystery_id UUID NOT NULL REFERENCES osint.mysteries(id) ON DELETE CASCADE,
  node_type TEXT NOT NULL CHECK (node_type IN ('cutscene','dialogue','level','det_gate','llm_gate')),
  label TEXT NOT NULL DEFAULT '',
  has_utterances BOOLEAN NOT NULL DEFAULT FALSE,
  xpos DOUBLE PRECISION NOT NULL,
  ypos DOUBLE PRECISION NOT NULL,
  -- Folded, type-specific scalars. Nullable during authoring (an author drops a
  -- node, then configures it); "required for its type" is a publish-time check.
  -- These exclusion CHECKs only stop a column being set on the wrong node_type.
  level_template_version_id UUID REFERENCES osint.level_template_versions(id),
  component_key TEXT,  -- cutscene: frontend component; gate: backend gate function
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CHECK (level_template_version_id IS NULL OR node_type = 'level'),
  CHECK (component_key IS NULL OR node_type IN ('cutscene','det_gate','llm_gate'))
);
CREATE INDEX story_nodes_mystery_idx ON osint.story_nodes (mystery_id);

CREATE TABLE osint.story_node_terminals (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  parent_node_id UUID NOT NULL REFERENCES osint.story_nodes(id) ON DELETE CASCADE,
  terminal_key TEXT NOT NULL,
  label TEXT NOT NULL DEFAULT '',
  -- The single wire out of this port. NULL = unwired (authoring, or deliberate
  -- end). SET NULL keeps the port when its target node is deleted.
  to_node_id UUID REFERENCES osint.story_nodes(id) ON DELETE SET NULL,
  sort_order INTEGER NOT NULL DEFAULT 0,
  UNIQUE (parent_node_id, terminal_key)
);
CREATE INDEX story_terminals_node_idx ON osint.story_node_terminals (parent_node_id);

-- One entrypoint per mystery. Nullable so nodes can be inserted before it is set
-- (avoids a chicken-and-egg with story_nodes.mystery_id).
ALTER TABLE osint.mysteries ADD COLUMN entry_node_id UUID REFERENCES osint.story_nodes(id) ON DELETE SET NULL;

COMMENT ON TABLE osint.story_nodes IS 'Nodes of a mystery story flow graph. Same-mystery integrity for terminal wiring is enforced in the repository (Phase 1).';
