-- 資料庫結構修復遷移腳本
-- 用於修復競賽相關表的結構問題

-- 1. 為 competition_award_types 表添加 order_index 欄位
ALTER TABLE `competition_award_types` 
ADD COLUMN `order_index` INT DEFAULT 0 AFTER `color`;

-- 為 order_index 添加索引
ALTER TABLE `competition_award_types` 
ADD INDEX `idx_order` (`order_index`);

-- 2. 為 competition_teams 表添加 registered_at 欄位
ALTER TABLE `competition_teams` 
ADD COLUMN `registered_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP AFTER `submitted_at`;

-- 3. 檢查並修復外鍵約束問題
-- 首先檢查是否有孤立的關聯記錄
DELETE FROM `competition_judges` 
WHERE `competition_id` NOT IN (SELECT `id` FROM `competitions`);

DELETE FROM `competition_teams` 
WHERE `competition_id` NOT IN (SELECT `id` FROM `competitions`);

DELETE FROM `competition_rules` 
WHERE `competition_id` NOT IN (SELECT `id` FROM `competitions`);

DELETE FROM `competition_award_types` 
WHERE `competition_id` NOT IN (SELECT `id` FROM `competitions`);

-- 4. 確保所有表都有正確的索引
-- competition_judges 表
ALTER TABLE `competition_judges` 
ADD INDEX IF NOT EXISTS `idx_competition` (`competition_id`),
ADD INDEX IF NOT EXISTS `idx_judge` (`judge_id`);

-- competition_teams 表
ALTER TABLE `competition_teams` 
ADD INDEX IF NOT EXISTS `idx_competition` (`competition_id`),
ADD INDEX IF NOT EXISTS `idx_team` (`team_id`);

-- competition_rules 表
ALTER TABLE `competition_rules` 
ADD INDEX IF NOT EXISTS `idx_competition` (`competition_id`),
ADD INDEX IF NOT EXISTS `idx_order` (`order_index`);

-- competition_award_types 表
ALTER TABLE `competition_award_types` 
ADD INDEX IF NOT EXISTS `idx_competition` (`competition_id`),
ADD INDEX IF NOT EXISTS `idx_order` (`order_index`),
ADD INDEX IF NOT EXISTS `idx_is_active` (`is_active`);

-- 5. 顯示修復結果
SELECT 'Database migration completed successfully' as status;
