package com.njcn.msgpush.module.push.service.retry;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.msgpush.module.push.dal.dataobject.retry.MessageRetryHistoryDO;
import com.njcn.msgpush.module.push.dal.mysql.retry.MessageRetryHistoryMapper;
import org.springframework.stereotype.Service;

/**
 * @author caozehui
 * @data 2026-03-04
 */
@Service
public class MessageRetryHistoryServiceImpl extends ServiceImpl<MessageRetryHistoryMapper, MessageRetryHistoryDO> implements MessageRetryHistoryService {
    @Override
    public boolean add(MessageRetryHistoryDO messageRetryHistoryDO) {
        return this.save(messageRetryHistoryDO);
    }

    public Integer getMaxRetrySequence(Long messageId) {
        MessageRetryHistoryDO one = this.lambdaQuery().eq(MessageRetryHistoryDO::getMessageId, messageId)
                .orderByDesc(MessageRetryHistoryDO::getRetrySequence)
                .last("limit 1")
                .one();
        return ObjectUtil.isNull(one) ? 0 : one.getRetrySequence() + 1;
    }

    @Override
    public boolean updateStatusAndErrorInfo(Long messageId, String status, String errorCode, String errorMsg) {
        MessageRetryHistoryDO one = this.lambdaQuery()
                .eq(MessageRetryHistoryDO::getMessageId, messageId)
                .orderByDesc(MessageRetryHistoryDO::getRetrySequence)
                .last("limit 1").one();
        if (ObjectUtil.isNotNull(one)) {
            one.setStatus(status);
            one.setErrorCode(errorCode);
            one.setErrorMsg(errorMsg);
            return this.updateById(one);
        }
        return false;
    }
}
