-- Content-addressed symbol index with base + overlay parent file maps.

ALTER TABLE symbol_index_parent_path ADD COLUMN kind TEXT NOT NULL DEFAULT 'base';
ALTER TABLE symbol_index_parent_path ADD COLUMN base_parent_id INTEGER REFERENCES symbol_index_parent_path(id) ON DELETE SET NULL;

CREATE TABLE IF NOT EXISTS symbol_file_blob (
  content_hash TEXT PRIMARY KEY,
  payload BLOB NOT NULL,
  tag_count INTEGER NOT NULL,
  created_at TEXT NOT NULL
);

-- Per-parent file map. content_hash NULL = tombstone (file removed in overlay; hides base entry).
CREATE TABLE IF NOT EXISTS symbol_parent_file_map (
  parent_id INTEGER NOT NULL,
  file_path TEXT NOT NULL,
  content_hash TEXT,
  PRIMARY KEY (parent_id, file_path),
  FOREIGN KEY (parent_id) REFERENCES symbol_index_parent_path(id) ON DELETE CASCADE,
  FOREIGN KEY (content_hash) REFERENCES symbol_file_blob(content_hash) ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS idx_symbol_parent_file_map_parent ON symbol_parent_file_map(parent_id);
CREATE INDEX IF NOT EXISTS idx_symbol_parent_file_map_hash ON symbol_parent_file_map(content_hash);

-- Shared tag index keyed by content hash for cross-file name lookups.
CREATE TABLE IF NOT EXISTS symbol_blob_tag_index (
  content_hash TEXT NOT NULL,
  name TEXT NOT NULL,
  role TEXT NOT NULL,
  kind TEXT NOT NULL,
  start_line INTEGER NOT NULL,
  start_column INTEGER NOT NULL,
  end_line INTEGER NOT NULL,
  end_column INTEGER NOT NULL,
  scope_start_line INTEGER,
  scope_start_column INTEGER,
  parent_scope_start_line INTEGER,
  parent_scope_start_column INTEGER,
  nav_target_path TEXT,
  scope_chain TEXT,
  PRIMARY KEY (content_hash, role, kind, name, start_line, start_column),
  FOREIGN KEY (content_hash) REFERENCES symbol_file_blob(content_hash) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_symbol_blob_tag_index_hash_name ON symbol_blob_tag_index(content_hash, name);

DROP TABLE IF EXISTS symbol_index_scope;
DROP TABLE IF EXISTS symbol_index_import;
DROP TABLE IF EXISTS symbol_index_tag;
