-- Add composite index for faster queries on payments table
-- Used for: SELECT SUM(stars_amount) WHERE user_id = ? AND status = 'COMPLETED'

-- First, try to drop the index if it exists (for idempotency)
-- This will fail silently if the index doesn't exist, which is fine
SET @drop_sql = CONCAT('DROP INDEX idx_payments_user_status ON payments');
SET @sql = IF(
    (SELECT COUNT(*) FROM information_schema.statistics 
     WHERE table_schema = DATABASE() 
     AND table_name = 'payments' 
     AND index_name = 'idx_payments_user_status') > 0,
    @drop_sql,
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Now create the index
CREATE INDEX idx_payments_user_status ON payments(user_id, status);

