-- V19: Markdown Links (Obsidian-style bidirectional links)
-- Adds support for wikilinks, markdown links, embeds, and backlink tracking
-- Table for storing extracted markdown links
CREATE TABLE IF NOT EXISTS markdown_links (
  id TEXT PRIMARY KEY NOT NULL,
  source_media_id TEXT NOT NULL,
  target_path TEXT NOT NULL, -- raw link target (wikilink or path)
  target_media_id TEXT, -- resolved media_id (nullable if unresolved)
  link_type TEXT NOT NULL, -- 'wikilink', 'markdown_link', 'embed'
  link_text TEXT, -- display text for the link
  line_number INTEGER, -- line number in source file
  context TEXT, -- surrounding text for preview
  created_at TIMESTAMPTZ NOT NULL,
  FOREIGN KEY (source_media_id) REFERENCES media_items (id) ON DELETE CASCADE,
  FOREIGN KEY (target_media_id) REFERENCES media_items (id) ON DELETE SET NULL
);

-- Index for efficient outgoing link queries (what does this note link to?)
CREATE INDEX idx_links_source ON markdown_links (source_media_id);

-- Index for efficient backlink queries (what links to this note?)
CREATE INDEX idx_links_target ON markdown_links (target_media_id);

-- Index for path-based resolution (finding unresolved links)
CREATE INDEX idx_links_target_path ON markdown_links (target_path);

-- Index for link type filtering
CREATE INDEX idx_links_type ON markdown_links (link_type);

-- Track when links were last extracted from a media item
ALTER TABLE media_items
ADD COLUMN links_extracted_at TIMESTAMPTZ;

-- Index for finding media items that need link extraction
CREATE INDEX idx_media_links_extracted ON media_items (links_extracted_at);
