-- Covering indexes for TUI list screen keyset pagination.
-- These supplement existing indexes from earlier migrations to
-- enable efficient ORDER BY ... LIMIT queries without temp B-tree sorts.

-- Issue list: default sort (updated_at DESC, iid DESC) with state filter.
-- Covers: WHERE project_id = ? AND state = ? ORDER BY updated_at DESC, iid DESC
CREATE INDEX IF NOT EXISTS idx_issues_tui_list
    ON issues(project_id, state, updated_at DESC, iid DESC);

-- MR list: default sort (updated_at DESC, iid DESC) with state filter.
CREATE INDEX IF NOT EXISTS idx_mrs_tui_list
    ON merge_requests(project_id, state, updated_at DESC, iid DESC);

-- Discussion list for entity detail screens: ordered by first note timestamp.
CREATE INDEX IF NOT EXISTS idx_discussions_issue_ordered
    ON discussions(issue_id, first_note_at DESC)
    WHERE issue_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_discussions_mr_ordered
    ON discussions(merge_request_id, first_note_at DESC)
    WHERE merge_request_id IS NOT NULL;

-- Notes within a discussion: chronological order for detail views.
CREATE INDEX IF NOT EXISTS idx_notes_discussion_ordered
    ON notes(discussion_id, created_at ASC);

-- Filter-path indexes for TUI filter bar queries.
-- Issues: author filter with state (covers WHERE author_username = ? AND state = ?).
CREATE INDEX IF NOT EXISTS idx_issues_author_state
    ON issues(author_username, state);

-- MRs: author filter with state.
CREATE INDEX IF NOT EXISTS idx_mrs_author_state
    ON merge_requests(author_username, state);

-- MRs: target branch filter with state.
CREATE INDEX IF NOT EXISTS idx_mrs_target_branch_state
    ON merge_requests(target_branch, state);

INSERT INTO schema_version (version, applied_at, description)
VALUES (27, strftime('%s', 'now') * 1000, 'TUI list screen covering indexes');
