-- Adds composite index for faster session validation
-- Safe to run multiple times: checks if index exists

-- MariaDB doesn't support IF NOT EXISTS for indexes uniformly across versions.
-- This pattern drops and recreates the index only if missing.

SET @idx_exists := (
  SELECT COUNT(1)
  FROM information_schema.STATISTICS
  WHERE table_schema = DATABASE()
    AND table_name = 'active_sessions'
    AND index_name = 'idx_code_session'
);

SET @stmt := IF(@idx_exists = 0,
  'CREATE INDEX idx_code_session ON active_sessions (code, session_id)',
  'DO_SELECT 1');

PREPARE stmt FROM @stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
