-- 创建优化历史功能相关表
-- 执行此脚本前请备份数据库

-- 1. 创建历史记录表
CREATE TABLE IF NOT EXISTS prompt_history (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
    user_id INT NOT NULL COMMENT '用户ID',
    wx_user_id INT COMMENT '微信用户ID',
    original_input TEXT NOT NULL COMMENT '原始输入',
    generated_prompt TEXT NOT NULL COMMENT '生成的提示词',
    template_id INT COMMENT '使用的模板ID',
    template_name VARCHAR(100) COMMENT '模板名称',
    generation_time INT COMMENT '生成耗时(毫秒)',
    satisfaction_rating TINYINT COMMENT '满意度评分(1-5)',
    tags JSON COMMENT '标签列表',
    is_favorite BOOLEAN DEFAULT FALSE COMMENT '是否收藏',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_user_id (user_id),
    INDEX idx_wx_user_id (wx_user_id),
    INDEX idx_created_at (created_at),
    INDEX idx_template_id (template_id),
    INDEX idx_is_favorite (is_favorite),
    INDEX idx_satisfaction_rating (satisfaction_rating)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='提示词历史记录表';

-- 2. 创建历史标签表
CREATE TABLE IF NOT EXISTS history_tags (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
    history_id INT NOT NULL COMMENT '历史记录ID',
    tag_name VARCHAR(50) NOT NULL COMMENT '标签名称',
    tag_type VARCHAR(20) DEFAULT 'custom' COMMENT '标签类型',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (history_id) REFERENCES prompt_history(id) ON DELETE CASCADE,
    INDEX idx_history_id (history_id),
    INDEX idx_tag_name (tag_name),
    INDEX idx_tag_type (tag_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='历史记录标签表';

-- 3. 创建用户统计表
CREATE TABLE IF NOT EXISTS user_statistics (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
    user_id INT UNIQUE NOT NULL COMMENT '用户ID',
    total_generations INT DEFAULT 0 COMMENT '总生成数',
    favorite_count INT DEFAULT 0 COMMENT '收藏数',
    avg_rating DECIMAL(3,2) DEFAULT 0.00 COMMENT '平均评分',
    last_generation_at TIMESTAMP NULL COMMENT '最后生成时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_user_id (user_id),
    INDEX idx_total_generations (total_generations),
    INDEX idx_last_generation_at (last_generation_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户统计信息表';

-- 4. 添加外键约束（如果存在相关表）
-- 注意：这些外键约束是可选的，根据实际数据库结构调整

-- 如果存在user表，添加外键约束
-- ALTER TABLE prompt_history ADD CONSTRAINT fk_prompt_history_user_id 
--     FOREIGN KEY (user_id) REFERENCES user(uid) ON DELETE CASCADE;

-- 如果存在wx_user表，添加外键约束
-- ALTER TABLE prompt_history ADD CONSTRAINT fk_prompt_history_wx_user_id 
--     FOREIGN KEY (wx_user_id) REFERENCES wx_user(id) ON DELETE SET NULL;

-- 如果存在prompt_template表，添加外键约束
-- ALTER TABLE prompt_history ADD CONSTRAINT fk_prompt_history_template_id 
--     FOREIGN KEY (template_id) REFERENCES prompt_template(id) ON DELETE SET NULL;

-- 5. 创建一些示例数据（可选）
-- INSERT INTO user_statistics (user_id, total_generations, favorite_count, avg_rating) 
-- VALUES (1, 0, 0, 0.00);

-- 6. 创建视图（可选，用于统计查询）
CREATE OR REPLACE VIEW history_statistics AS
SELECT 
    h.user_id,
    COUNT(*) as total_count,
    COUNT(CASE WHEN h.is_favorite = TRUE THEN 1 END) as favorite_count,
    AVG(h.satisfaction_rating) as avg_rating,
    MAX(h.created_at) as last_generation_at,
    COUNT(CASE WHEN h.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as week_count,
    COUNT(CASE WHEN h.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as month_count
FROM prompt_history h
GROUP BY h.user_id;

-- 7. 创建存储过程（可选，用于清理旧数据）
DELIMITER //
CREATE PROCEDURE CleanOldHistory(IN days_to_keep INT)
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        RESIGNAL;
    END;
    
    START TRANSACTION;
    
    -- 删除指定天数前的历史记录
    DELETE FROM prompt_history 
    WHERE created_at < DATE_SUB(NOW(), INTERVAL days_to_keep DAY);
    
    -- 更新用户统计
    UPDATE user_statistics us
    SET 
        total_generations = (
            SELECT COUNT(*) FROM prompt_history h 
            WHERE h.user_id = us.user_id
        ),
        favorite_count = (
            SELECT COUNT(*) FROM prompt_history h 
            WHERE h.user_id = us.user_id AND h.is_favorite = TRUE
        ),
        avg_rating = (
            SELECT AVG(h.satisfaction_rating) FROM prompt_history h 
            WHERE h.user_id = us.user_id AND h.satisfaction_rating IS NOT NULL
        ),
        last_generation_at = (
            SELECT MAX(h.created_at) FROM prompt_history h 
            WHERE h.user_id = us.user_id
        ),
        updated_at = NOW()
    WHERE us.user_id IN (
        SELECT DISTINCT user_id FROM prompt_history
    );
    
    COMMIT;
END //
DELIMITER ;

-- 8. 创建触发器（可选，用于自动更新统计）
DELIMITER //
CREATE TRIGGER update_user_stats_after_insert
AFTER INSERT ON prompt_history
FOR EACH ROW
BEGIN
    INSERT INTO user_statistics (user_id, total_generations, favorite_count, avg_rating, last_generation_at)
    VALUES (NEW.user_id, 1, IF(NEW.is_favorite, 1, 0), NEW.satisfaction_rating, NEW.created_at)
    ON DUPLICATE KEY UPDATE
        total_generations = total_generations + 1,
        favorite_count = favorite_count + IF(NEW.is_favorite, 1, 0),
        avg_rating = (
            SELECT AVG(satisfaction_rating) 
            FROM prompt_history 
            WHERE user_id = NEW.user_id AND satisfaction_rating IS NOT NULL
        ),
        last_generation_at = NEW.created_at,
        updated_at = NOW();
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER update_user_stats_after_update
AFTER UPDATE ON prompt_history
FOR EACH ROW
BEGIN
    UPDATE user_statistics 
    SET 
        total_generations = (
            SELECT COUNT(*) FROM prompt_history WHERE user_id = NEW.user_id
        ),
        favorite_count = (
            SELECT COUNT(*) FROM prompt_history 
            WHERE user_id = NEW.user_id AND is_favorite = TRUE
        ),
        avg_rating = (
            SELECT AVG(satisfaction_rating) FROM prompt_history 
            WHERE user_id = NEW.user_id AND satisfaction_rating IS NOT NULL
        ),
        updated_at = NOW()
    WHERE user_id = NEW.user_id;
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER update_user_stats_after_delete
AFTER DELETE ON prompt_history
FOR EACH ROW
BEGIN
    UPDATE user_statistics 
    SET 
        total_generations = (
            SELECT COUNT(*) FROM prompt_history WHERE user_id = OLD.user_id
        ),
        favorite_count = (
            SELECT COUNT(*) FROM prompt_history 
            WHERE user_id = OLD.user_id AND is_favorite = TRUE
        ),
        avg_rating = (
            SELECT AVG(satisfaction_rating) FROM prompt_history 
            WHERE user_id = OLD.user_id AND satisfaction_rating IS NOT NULL
        ),
        updated_at = NOW()
    WHERE user_id = OLD.user_id;
END //
DELIMITER ;

-- 执行完成提示
SELECT '历史记录表创建完成！' as message;
