-- 签到插件数据库升级脚本
-- 版本: 1.1.0
-- 更新内容:
--   v1.0.0: 添加城市字段
--   v1.1.0: 添加积分变动记录表

-- ============================================
-- v1.0.0 - 添加城市字段（如果已执行可跳过）
-- ============================================

-- 添加城市字段到 user_signin 表（如果不存在）
-- ALTER TABLE `user_signin`
-- ADD COLUMN `city` VARCHAR(50) DEFAULT '' COMMENT '用户城市'
-- AFTER `nickname`;

-- 添加城市字段的索引
-- ALTER TABLE `user_signin`
-- ADD INDEX `idx_city` (`city`);

-- ============================================
-- v1.1.0 - 添加积分变动记录表
-- ============================================

-- 创建积分变动记录表
CREATE TABLE IF NOT EXISTS `points_history` (
    `id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '自增ID',
    `wxid` VARCHAR(50) NOT NULL COMMENT '用户微信ID',
    `nickname` VARCHAR(100) DEFAULT '' COMMENT '用户昵称',
    `change_type` VARCHAR(20) NOT NULL COMMENT '变动类型: signin(签到), bonus(奖励), consume(消费), admin(管理员调整), other(其他)',
    `points_change` INT NOT NULL COMMENT '积分变动数量（正数增加，负数减少）',
    `points_before` INT NOT NULL COMMENT '变动前积分',
    `points_after` INT NOT NULL COMMENT '变动后积分',
    `description` VARCHAR(200) DEFAULT '' COMMENT '变动说明',
    `related_id` VARCHAR(50) DEFAULT '' COMMENT '关联ID（如订单号、签到记录ID等）',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '变动时间',
    INDEX `idx_wxid` (`wxid`),
    INDEX `idx_change_type` (`change_type`),
    INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='积分变动记录表';

-- 创建积分统计视图
CREATE OR REPLACE VIEW `v_points_summary` AS
SELECT
    wxid,
    nickname,
    points as current_points,
    total_signin_days,
    signin_streak,
    (SELECT COALESCE(SUM(points_change), 0) FROM points_history ph WHERE ph.wxid = us.wxid AND points_change > 0) as total_earned,
    (SELECT COALESCE(SUM(ABS(points_change)), 0) FROM points_history ph WHERE ph.wxid = us.wxid AND points_change < 0) as total_spent
FROM user_signin us;

-- ============================================
-- 可选：从历史签到记录迁移数据（仅首次升级时执行一次）
-- ============================================
-- INSERT INTO points_history (wxid, nickname, change_type, points_change, points_before, points_after, description, related_id, created_at)
-- SELECT
--     sr.wxid,
--     sr.nickname,
--     'signin' as change_type,
--     sr.points_earned as points_change,
--     0 as points_before,
--     0 as points_after,
--     CONCAT('签到获得 ', sr.points_earned, ' 积分（连续', sr.signin_streak, '天）') as description,
--     sr.signin_date as related_id,
--     sr.created_at
-- FROM signin_records sr
-- WHERE NOT EXISTS (
--     SELECT 1 FROM points_history ph
--     WHERE ph.wxid = sr.wxid AND ph.related_id = sr.signin_date AND ph.change_type = 'signin'
-- );

-- 验证升级结果
-- SELECT '积分变动记录表' as table_name, COUNT(*) as record_count FROM points_history;
