package com.cool.store.mq.consumer.listener;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.cool.store.constants.CommonConstants;
import com.cool.store.service.visit.VisitRecordService;
import com.cool.store.utils.RedisUtilPool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 拜访记录失效listener
 * </p>
 *
 * @author wangff
 * @since 2026/1/26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VisitRecordListener implements MessageListener {
    private final RedisUtilPool redisUtilPool;
    private final VisitRecordService visitRecordService;


    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String text = new String(message.getBody());
        if (StringUtils.isBlank(text)) {
            log.info("消息体为空,tag:{},messageId:{}", message.getTag(), message.getMsgID());
            return Action.CommitMessage;
        }
        String lockKey = "VisitRecordListener:" + message.getMsgID();
        boolean lock = redisUtilPool.setNxExpire(lockKey, message.getMsgID(), CommonConstants.NORMAL_LOCK_TIMES);
        if (lock) {
            try {
                visitRecordService.recordInvalid(Long.valueOf(text));
            } catch (Exception e) {
                log.error("VisitRecordListener consume error", e);
                return Action.ReconsumeLater;
            } finally {
                redisUtilPool.delKey(lockKey);
            }
            log.info("消费成功,tag:{},messageId:{},reqBody={}", message.getTag(), message.getMsgID(), text);
            return Action.CommitMessage;
        }
        return Action.ReconsumeLater;
    }
}
