package org.xyzh.achievement.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.xyzh.api.achievement.AchievementService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.event.AchievementEvent;
import org.xyzh.common.dto.usercenter.TbUserAchievement;

import java.util.List;

/**
 * @description 成就事件监听器 - 监听业务事件并自动触发成就检测
 * @filename AchievementEventListener.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-24
 */
@Component
public class AchievementEventListener {

    private static final Logger logger = LoggerFactory.getLogger(AchievementEventListener.class);

    @Autowired
    private AchievementService achievementService;

    /**
     * 监听成就事件
     * 使用@Async异步处理，避免阻塞主业务流程
     */
    @Async
    @EventListener
    public void handleAchievementEvent(AchievementEvent event) {
        try {
            logger.debug("接收到成就事件: {}", event);
            
            // 处理成就事件
            ResultDomain<TbUserAchievement> result = achievementService.processAchievementEvent(event);

            if (result.isSuccess() && result.getDataList() != null && !result.getDataList().isEmpty()) {
                logger.info("用户 {} 通过事件 {} 获得 {} 个新成就", 
                    event.getUserID(), 
                    event.getEventType(), 
                    result.getDataList().size());
                // 这里可以添加通知逻辑，如发送消息给用户
                notifyUserAboutNewAchievements(event.getUserID(), result.getDataList());
            }
        } catch (Exception e) {
            logger.error("处理成就事件异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 通知用户获得新成就（示例方法，需要根据实际业务实现）
     */
    private void notifyUserAboutNewAchievements(String userID, List<TbUserAchievement> achievements) {
        // TODO: 实现通知逻辑
        // 1. 发送系统消息
        // 2. 发送推送通知
        // 3. 记录通知日志
        logger.info("通知用户 {} 获得成就，数量: {}", userID, achievements.size());
    }
}

