-- V51: 回填历史奖励记录的部门ID
-- 用途: 修复奖励数据权限关键字段缺失，确保部门数据过滤正常工作
-- 策略: 通过关联活动表，从活动继承部门ID到奖励记录
-- 注意: 此迁移可重复执行（幂等）

-- 首先为有活动ID的奖励记录回填department_id
UPDATE user_rewards ur
SET department_id = a.department_id
FROM activities a
WHERE ur.department_id IS NULL
AND ur.activity_id = a.id
AND ur.activity_id IS NOT NULL;

-- 记录回填日志（可选，便于审计）
-- INSERT INTO sys_audit_log (user_id, action, resource_type, resource_id, details, created_at)
-- SELECT 0, 'BACKFILL_DEPARTMENT_ID', 'user_rewards', ur.id,
--        CONCAT('回填department_id=', a.department_id, ' from activity_id=', ur.activity_id),
--        NOW(3)
-- FROM user_rewards ur
-- INNER JOIN activities a ON ur.activity_id = a.id
-- WHERE ur.department_id IS NULL
-- AND ur.activity_id IS NOT NULL;
