-- Migration: Add search_key column and optimize indices
-- Date: 2026-02-07
-- Purpose: Enable fast LOINC/gene/modality search for MCP API

-- ============================================================================
-- 1. Add search_key column
-- ============================================================================

ALTER TABLE entries ADD COLUMN search_key TEXT;

-- ============================================================================
-- 2. Drop redundant indices
-- ============================================================================

-- Redundant with idx_entries_search_key (which covers dossier_id, category)
DROP INDEX IF EXISTS idx_entries_dossier;

-- Redundant with idx_entries_search_key (which covers dossier_id, category, search_key)
DROP INDEX IF EXISTS idx_entries_dossier_category;

-- Redundant after code fix to always include dossier_id in parent queries
DROP INDEX IF EXISTS idx_entries_parent;

-- ============================================================================
-- 3. Add new index for search_key
-- ============================================================================

CREATE INDEX idx_entries_search_key
ON entries(dossier_id, category, search_key);

-- ============================================================================
-- 4. Backfill search_key from existing data
-- ============================================================================

-- Labs: Extract LOINC from data.loinc
UPDATE entries
SET search_key = json_extract(data, '$.loinc')
WHERE category = 3
  AND search_key IS NULL
  AND json_extract(data, '$.loinc') IS NOT NULL;

-- Genome: Extract gene from data.gene
UPDATE entries
SET search_key = json_extract(data, '$.gene')
WHERE category = 4
  AND search_key IS NULL
  AND json_extract(data, '$.gene') IS NOT NULL;

-- ============================================================================
-- Final index state:
-- ============================================================================
-- 1. sqlite_autoindex_entries_1      (entry_id)                    PRIMARY KEY
-- 2. idx_entries_dossier_parent      (dossier_id, parent_id)       KEPT
-- 3. idx_entries_search_key          (dossier_id, category, search_key)  NEW
-- ============================================================================
