-- Additional performance optimization indexes
-- Migration: 008_additional_performance_indexes

-- =====================================================
-- KANBAN QUERY OPTIMIZATION
-- =====================================================

-- Composite index for kanban board queries
-- Covers: WHERE residence_id IN ? AND is_archived = false
-- with ordering by due_date, next_due_date
CREATE INDEX IF NOT EXISTS idx_task_kanban_composite
    ON task_task (residence_id, is_archived, is_cancelled, next_due_date, due_date)
    WHERE is_archived = false;

-- =====================================================
-- COMPLETION QUERY OPTIMIZATION
-- =====================================================

-- Ordering index for completion queries (most recent first)
CREATE INDEX IF NOT EXISTS idx_completion_task_date
    ON task_taskcompletion (task_id, completed_at DESC);

-- =====================================================
-- SHARE CODE OPTIMIZATION
-- =====================================================

-- Unique index for active share code lookups
CREATE UNIQUE INDEX IF NOT EXISTS idx_sharecode_code_active
    ON residence_residencesharecode (code)
    WHERE is_active = true;

-- =====================================================
-- RESIDENCE USER ACCESS OPTIMIZATION
-- =====================================================

-- Index for residence user membership queries (used by FindResidenceIDsByUser)
CREATE INDEX IF NOT EXISTS idx_residence_users_user_residence
    ON residence_residence_users (user_id, residence_id);

-- =====================================================
-- TASK IN_PROGRESS QUERIES
-- =====================================================

-- Index for in_progress task queries (kanban "In Progress" column)
CREATE INDEX IF NOT EXISTS idx_task_in_progress
    ON task_task (residence_id, in_progress)
    WHERE in_progress = true AND is_cancelled = false AND is_archived = false;
