-- 数据库迁移脚本：为link_task表添加首次选区时间字段
-- 执行时间：2025-01-XX
-- 说明：记录链接首次选区的准确时间，便于跟踪和分析

-- 为link_task表添加首次选区时间字段
ALTER TABLE `link_task` 
ADD COLUMN `first_region_select_at` datetime(3) NULL DEFAULT NULL COMMENT '首次选区时间' AFTER `qr_expire_at`;

-- 添加索引以优化查询性能
ALTER TABLE `link_task` 
ADD INDEX `idx_first_region_select` (`first_region_select_at` ASC);

-- 为现有USING状态的记录回填首次选区时间（使用qr_created_at作为首次选区时间）
UPDATE `link_task` 
SET `first_region_select_at` = `qr_created_at`
WHERE `status` = 'USING' 
  AND `qr_created_at` IS NOT NULL 
  AND `first_region_select_at` IS NULL;

-- 验证表结构变更
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = DATABASE() 
  AND TABLE_NAME = 'link_task' 
  AND COLUMN_NAME = 'first_region_select_at'
ORDER BY ORDINAL_POSITION;

-- 验证数据回填结果
SELECT 
    COUNT(*) as total_using_links,
    COUNT(first_region_select_at) as links_with_first_select_time,
    COUNT(qr_created_at) as links_with_qr_time
FROM `link_task` 
WHERE `status` = 'USING';
