CREATE TABLE IF NOT EXISTS files (
    id INTEGER PRIMARY KEY,
    path TEXT NOT NULL UNIQUE,
    LANGUAGE TEXT NOT NULL,
    package TEXT,
    hash TEXT NOT NULL,
    indexed_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS symbols (
    id INTEGER PRIMARY KEY,
    file_id INTEGER NOT NULL REFERENCES files (id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    kind TEXT NOT NULL CHECK (
        kind IN (
            'function',
            'method',
            'class',
            'type',
            'reference',
            'interface',
            'constant',
            'variable',
            'constructor'
        )
    ),
    line INTEGER NOT NULL,
    line_end INTEGER,
    col INTEGER,
    col_end INTEGER,
    exported BOOLEAN,
    parent_id INTEGER REFERENCES symbols (id),
    UNIQUE (file_id, name, kind, line)
);

CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols (name);

CREATE INDEX IF NOT EXISTS idx_symbols_kind ON symbols (kind);

CREATE INDEX IF NOT EXISTS idx_symbols_file_line ON symbols (file_id, line);

CREATE INDEX IF NOT EXISTS idx_symbols_parent ON symbols (parent_id);

CREATE INDEX IF NOT EXISTS idx_symbols_exported ON symbols (exported, kind);

CREATE INDEX IF NOT EXISTS idx_files_path ON files (path);

CREATE INDEX IF NOT EXISTS idx_files_language ON files (LANGUAGE);

CREATE INDEX IF NOT EXISTS idx_files_package ON files (package);

-- FTS5 virtual table for full-text search of file contents.
-- content is stored here (not external content), keyed by file_id.
CREATE VIRTUAL TABLE IF NOT EXISTS file_contents USING fts5 (
    file_id UNINDEXED,
    content,
    tokenize = 'porter unicode61'
);
