package com.tashow.cloud.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tashow.cloud.app.mapper.BuriedPointFailRecordMapper;
import com.tashow.cloud.app.model.MqMessageRecord;
import com.tashow.cloud.app.mq.message.BuriedMessages;
import com.tashow.cloud.app.mq.producer.buriedPoint.BuriedPointProducer;
import com.tashow.cloud.common.util.json.JsonUtils;
import com.tashow.cloud.mq.retry.MessageRetryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 埋点失败记录服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BuriedPointFailRecordService implements MessageRetryService<MqMessageRecord> {

    private final BuriedPointFailRecordMapper buriedPointFailRecordMapper;
    private final BuriedPointProducer buriedPointProducer;

    /**
     * 获取未处理的失败记录
     */
    @Override
    public List<MqMessageRecord> getUnprocessedRecords() {
        LambdaQueryWrapper<MqMessageRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MqMessageRecord::getStatus, MqMessageRecord.STATUS_FAILED)
                .orderByAsc(MqMessageRecord::getCreateTime);
        return buriedPointFailRecordMapper.selectList(queryWrapper);
    }

    /**
     * 重试失败消息
     */
    @Override
    public void retryFailedMessage(Integer recordId) {
        try {
            Long id = Long.valueOf(recordId);
            MqMessageRecord record = buriedPointFailRecordMapper.selectById(id);
            BuriedMessages message = JsonUtils.parseObject(record.getMessageContent(), BuriedMessages.class);
            buriedPointProducer.asyncSendMessage(message);
        } catch (Exception e) {
            log.error("[埋点重试] 重试失败", e);
        }
    }
} 