SET @chat_log_template_round_variant_index = (
    SELECT CASE
               WHEN COUNT(1) > 0 THEN 'SELECT 1'
               ELSE 'ALTER TABLE `chat_log_template` ADD INDEX `idx_chat_log_round_variant` (`session_id`, `round_id`, `message_kind`, `variant_index`, `created`, `id`)'
           END
    FROM information_schema.statistics
    WHERE table_schema = DATABASE()
      AND table_name = 'chat_log_template'
      AND index_name = 'idx_chat_log_round_variant'
);

PREPARE stmt_chat_log_template_round_variant_index FROM @chat_log_template_round_variant_index;
EXECUTE stmt_chat_log_template_round_variant_index;
DEALLOCATE PREPARE stmt_chat_log_template_round_variant_index;

DROP PROCEDURE IF EXISTS migrate_chat_log_round_variant_index;

CREATE PROCEDURE migrate_chat_log_round_variant_index()
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE v_table_name VARCHAR(128);
    DECLARE table_cursor CURSOR FOR
        SELECT table_name
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name LIKE 'chat_log\_%'
          AND table_name <> 'chat_log_template';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN table_cursor;
    read_loop: LOOP
        FETCH table_cursor INTO v_table_name;
        IF done = 1 THEN
            LEAVE read_loop;
        END IF;

        IF NOT EXISTS (
            SELECT 1
            FROM information_schema.statistics
            WHERE table_schema = DATABASE()
              AND table_name = v_table_name
              AND index_name = 'idx_chat_log_round_variant'
        ) THEN
            SET @chat_log_round_variant_index = CONCAT(
                'ALTER TABLE `',
                v_table_name,
                '` ADD INDEX `idx_chat_log_round_variant` (`session_id`, `round_id`, `message_kind`, `variant_index`, `created`, `id`)'
            );
            PREPARE stmt_chat_log_round_variant_index FROM @chat_log_round_variant_index;
            EXECUTE stmt_chat_log_round_variant_index;
            DEALLOCATE PREPARE stmt_chat_log_round_variant_index;
        END IF;
    END LOOP;
    CLOSE table_cursor;
END;

CALL migrate_chat_log_round_variant_index();
DROP PROCEDURE IF EXISTS migrate_chat_log_round_variant_index;
