-- ============================================================
-- V5: 乐读派 AI 绘本创作系统集成
-- 1. t_ugc_work：status VARCHAR → INT（先转换旧数据再改类型）
-- 2. 新增乐读派关联字段
-- 3. 新增索引
-- 4. Webhook 幂等去重表
-- ============================================================

-- 1. t_ugc_work：status VARCHAR → INT
-- 先将旧字符串状态值转换为整数值
UPDATE t_ugc_work SET status = '0'  WHERE status = 'draft';
UPDATE t_ugc_work SET status = '1'  WHERE status = 'pending_review';
UPDATE t_ugc_work SET status = '2'  WHERE status = 'processing';
UPDATE t_ugc_work SET status = '3'  WHERE status = 'published';
UPDATE t_ugc_work SET status = '-1' WHERE status = 'rejected';
UPDATE t_ugc_work SET status = '-2' WHERE status = 'taken_down';
-- 其他未识别的值统一设为 0(DRAFT)
UPDATE t_ugc_work SET status = '0' WHERE status NOT REGEXP '^-?[0-9]+$';

ALTER TABLE t_ugc_work MODIFY COLUMN status INT NOT NULL DEFAULT 0
    COMMENT '创作状态：-1=FAILED, 0=DRAFT, 1=PENDING, 2=PROCESSING, 3=COMPLETED, 4=CATALOGED, 5=DUBBED';

-- 2. 新增乐读派关联字段
ALTER TABLE t_ugc_work ADD COLUMN remote_work_id VARCHAR(64) DEFAULT NULL COMMENT '乐读派远程作品ID' AFTER user_id;
ALTER TABLE t_ugc_work ADD COLUMN progress INT DEFAULT 0 COMMENT 'AI创作进度百分比' AFTER ai_meta;
ALTER TABLE t_ugc_work ADD COLUMN progress_message VARCHAR(200) DEFAULT NULL COMMENT '进度描述' AFTER progress;
ALTER TABLE t_ugc_work ADD COLUMN style VARCHAR(100) DEFAULT NULL COMMENT '创作风格' AFTER progress_message;
ALTER TABLE t_ugc_work ADD COLUMN author_name VARCHAR(100) DEFAULT NULL COMMENT '作者' AFTER style;
ALTER TABLE t_ugc_work ADD COLUMN fail_reason VARCHAR(500) DEFAULT NULL COMMENT '失败原因' AFTER author_name;

-- 3. 新增索引
ALTER TABLE t_ugc_work ADD UNIQUE INDEX uk_remote_work_id (remote_work_id);
ALTER TABLE t_ugc_work ADD INDEX idx_user_status (user_id, status);

-- 4. Webhook 幂等去重表
CREATE TABLE IF NOT EXISTS t_leai_webhook_event (
    id BIGINT NOT NULL AUTO_INCREMENT,
    event_id VARCHAR(128) NOT NULL COMMENT '事件唯一ID (X-Webhook-Id)',
    event_type VARCHAR(64) NOT NULL COMMENT '事件类型',
    remote_work_id VARCHAR(64) DEFAULT NULL COMMENT '乐读派作品ID',
    payload JSON DEFAULT NULL COMMENT '事件原始载荷',
    processed TINYINT NOT NULL DEFAULT 1 COMMENT '是否已处理',
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE INDEX uk_event_id (event_id),
    INDEX idx_remote_work_id (remote_work_id),
    INDEX idx_create_time (create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='乐读派Webhook事件去重表';
