-- 步骤2：更新生产环境数据库播课字段
-- 日期: 2025-10-14
-- 说明: 清理旧的异步状态字段，只保留必要的播课字段
-- 执行前请先运行 step1_check.sql 查看当前字段情况

USE kaopeilian;

-- 删除不再需要的字段
-- 如果字段不存在会报错，可以忽略错误继续执行

-- 删除 broadcast_status
SET @sql = IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = 'kaopeilian' 
     AND TABLE_NAME = 'courses' 
     AND COLUMN_NAME = 'broadcast_status') > 0,
    'ALTER TABLE courses DROP COLUMN broadcast_status',
    'SELECT "broadcast_status 不存在，跳过" AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 删除 broadcast_task_id
SET @sql = IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = 'kaopeilian' 
     AND TABLE_NAME = 'courses' 
     AND COLUMN_NAME = 'broadcast_task_id') > 0,
    'ALTER TABLE courses DROP COLUMN broadcast_task_id',
    'SELECT "broadcast_task_id 不存在，跳过" AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 删除 broadcast_error_message
SET @sql = IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = 'kaopeilian' 
     AND TABLE_NAME = 'courses' 
     AND COLUMN_NAME = 'broadcast_error_message') > 0,
    'ALTER TABLE courses DROP COLUMN broadcast_error_message',
    'SELECT "broadcast_error_message 不存在，跳过" AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 添加必要字段（如果不存在）

-- 添加 broadcast_audio_url
SET @sql = IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = 'kaopeilian' 
     AND TABLE_NAME = 'courses' 
     AND COLUMN_NAME = 'broadcast_audio_url') = 0,
    'ALTER TABLE courses ADD COLUMN broadcast_audio_url VARCHAR(500) NULL COMMENT ''播课音频URL''',
    'SELECT "broadcast_audio_url 已存在，跳过" AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 添加 broadcast_generated_at
SET @sql = IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = 'kaopeilian' 
     AND TABLE_NAME = 'courses' 
     AND COLUMN_NAME = 'broadcast_generated_at') = 0,
    'ALTER TABLE courses ADD COLUMN broadcast_generated_at DATETIME NULL COMMENT ''播课生成时间''',
    'SELECT "broadcast_generated_at 已存在，跳过" AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 验证最终字段
SELECT '=== 更新后的播课字段 ===' AS info;
SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'kaopeilian' 
AND TABLE_NAME = 'courses' 
AND COLUMN_NAME LIKE 'broadcast%'
ORDER BY COLUMN_NAME;

