package com.red.circle.mq.rocket.business.failmessage.impl;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.mq.rocket.business.failmessage.RocketMqFailMessageDetail;
import com.red.circle.mq.rocket.business.failmessage.RocketMqFailMessageKeys;
import com.red.circle.mq.rocket.business.failmessage.RocketMqFailMessageQueryService;
import com.red.circle.tool.core.collection.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * RocketMQ 失败消息查询服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RocketMqFailMessageQueryServiceImpl implements RocketMqFailMessageQueryService {

    private final RedisService redisService;

    @Override
    public List<RocketMqFailMessageDetail> getPendingMessagesByTag(String tag, int limit) {
        try {
            // 1. 从 Set 中获取该 tag 的所有 bizNo
            String tagGroupKey = RocketMqFailMessageKeys.getTagGroupKey(tag);
            Set<String> bizNos = redisService.setGet(tagGroupKey).stream().map(String::valueOf).collect(Collectors.toSet());

            if (CollectionUtils.isEmpty(bizNos)) {
                return List.of();
            }

            long currentTime = System.currentTimeMillis();

            // 2. 批量获取详情并过滤
            return bizNos.stream()
                    .limit(limit)
                    .map(this::getMessageByBizNo)
                    .filter(Objects::nonNull)
                    .filter(msg -> msg.getStatus() == 0) // 待重试
                    .filter(msg -> msg.getNextRetryTime() != null && msg.getNextRetryTime() <= currentTime)
                    .collect(Collectors.toList());

        } catch (Exception e) {
            log.error("根据Tag查询待重试消息异常，tag={}, error={}", tag, e.getMessage(), e);
            return List.of();
        }
    }

    @Override
    public RocketMqFailMessageDetail getMessageByBizNo(String bizNo) {
        try {
            String messageKey = RocketMqFailMessageKeys.getMessageDetailKey(bizNo);
            return redisService.hashGet(messageKey, "detail", RocketMqFailMessageDetail.class);
        } catch (Exception e) {
            log.error("获取失败消息详情异常，bizNo={}, error={}", bizNo, e.getMessage(), e);
            return null;
        }
    }
}
