-- 920_add_performance_indexes.sql
-- Add performance-critical indexes for frequently queried fields
-- BE-DB-001: Add database indexes for performance-critical queries

-- Index on tracks.status for filtering by status (uploading, processing, ready, error)
CREATE INDEX IF NOT EXISTS idx_tracks_status ON public.tracks(status) WHERE status IS NOT NULL;

-- Index on tracks.user_id (legacy field, but still used in some queries)
-- Note: creator_id already has an index (idx_tracks_creator_id)
CREATE INDEX IF NOT EXISTS idx_tracks_user_id ON public.tracks(user_id) WHERE user_id IS NOT NULL;

-- Composite index for common track queries: user_id + status
CREATE INDEX IF NOT EXISTS idx_tracks_user_id_status ON public.tracks(user_id, status) WHERE user_id IS NOT NULL AND status IS NOT NULL;

-- Index on tracks.stream_status for filtering by stream processing status
CREATE INDEX IF NOT EXISTS idx_tracks_stream_status ON public.tracks(stream_status) WHERE stream_status IS NOT NULL;

-- Index on tracks.is_public for public/private filtering (legacy field)
CREATE INDEX IF NOT EXISTS idx_tracks_is_public ON public.tracks(is_public) WHERE is_public = true;

-- Additional indexes for common query patterns

-- Index on playlists.is_public for public playlist queries
-- Note: visibility already has an index (idx_playlists_visibility)
CREATE INDEX IF NOT EXISTS idx_playlists_is_public ON public.playlists(is_public) WHERE is_public = true;

-- Index on user_sessions.is_active for active session lookups
CREATE INDEX IF NOT EXISTS idx_user_sessions_is_active ON public.user_sessions(is_active) WHERE is_active = true;

-- Index on user_sessions.user_id + is_active for common session queries
CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id_active ON public.user_sessions(user_id, is_active) WHERE is_active = true;

-- Index on sessions table (if it exists separately from user_sessions)
-- Note: This uses IF NOT EXISTS to avoid errors if table doesn't exist
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'sessions') THEN
        CREATE INDEX IF NOT EXISTS idx_sessions_user_id_active ON public.sessions(user_id) WHERE revoked_at IS NULL;
    END IF;
END $$;

