-- [2026-01-08] 添加活动记录唯一约束
-- 防止同一实体的相同类型活动被重复记录（Kafka 消息重试场景）
-- 注意：需要先清理已有重复数据

-- 清理已有的重复数据（保留最早的记录）
DELETE FROM system_activities a
USING (
    SELECT activity_type, related_entity_type, related_entity_id, MIN(activity_id) as min_id
    FROM system_activities
    WHERE related_entity_type IS NOT NULL AND related_entity_id IS NOT NULL
    GROUP BY activity_type, related_entity_type, related_entity_id
    HAVING COUNT(*) > 1
) b
WHERE a.activity_type = b.activity_type
  AND a.related_entity_type = b.related_entity_type
  AND a.related_entity_id = b.related_entity_id
  AND a.activity_id != b.min_id;

-- 创建唯一约束
CREATE UNIQUE INDEX "uk_sa_entity_activity" ON "system_activities"("activity_type", "related_entity_type", "related_entity_id");
