SET FOREIGN_KEY_CHECKS=0;

-- WARNING: This script is NOT idempotent! MAKE A BACKUP BEFORE RUNNING THIS SCRIPT!

-- Drop UK idac_user_vs_info_uk
ALTER TABLE idac_user_vs_info
DROP FOREIGN KEY idac_user_vs_info_ibfk_1,
DROP INDEX idac_user_vs_info_uk;

-- Drop the new columns added to the original table
ALTER TABLE idac_user_vs_info
DROP COLUMN battle_mode,
DROP COLUMN invalid,
DROP COLUMN str,
DROP COLUMN str_now,
DROP COLUMN lose_now;

-- Add back the old columns to the original table
ALTER TABLE idac_user_vs_info
ADD COLUMN group_key VARCHAR(25),
ADD COLUMN win_flg INT,
ADD COLUMN style_car_id INT,
ADD COLUMN course_id INT,
ADD COLUMN course_day INT,
ADD COLUMN players_num INT,
ADD COLUMN winning INT,
ADD COLUMN advantage_1 INT,
ADD COLUMN advantage_2 INT,
ADD COLUMN advantage_3 INT,
ADD COLUMN advantage_4 INT,
ADD COLUMN select_course_id INT,
ADD COLUMN select_course_day INT,
ADD COLUMN select_course_random INT,
ADD COLUMN matching_success_sec INT,
ADD COLUMN boost_flag INT;

-- Delete the data from the original table where group_key is NULL
DELETE FROM idac_user_vs_info
WHERE group_key IS NULL;

-- Insert data back to the original table from idac_user_vs_course_info
INSERT INTO idac_user_vs_info (user, group_key, win_flg, style_car_id, course_id, course_day, players_num, winning, advantage_1, advantage_2, advantage_3, advantage_4, select_course_id, select_course_day, select_course_random, matching_success_sec, boost_flag, vs_history, break_count, break_penalty_flag)
SELECT user, CONCAT(FLOOR(RAND()*(99999999999999-10000000000000+1)+10000000000000), 'A69E01A8888'), 0, 0, course_id, 0, 0, vs_cnt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
FROM idac_user_vs_course_info;

-- Add back the constraints and indexes to the original table
ALTER TABLE idac_user_vs_info
ADD CONSTRAINT idac_user_vs_info_ibfk_1 FOREIGN KEY (user) REFERENCES aime_user(id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD UNIQUE KEY idac_user_vs_info_uk (user, group_key);

-- Drop the new table idac_user_vs_course_info
DROP TABLE IF EXISTS idac_user_vs_course_info;

SET FOREIGN_KEY_CHECKS=1;
