package com.munjaon.client.mssql.service;

import com.munjaon.client.model.MunjaonMsg;
import com.munjaon.client.mssql.mapper.MssqlMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class MssqlService {
    private final MssqlMapper deliverBMapper;

    public boolean checkTableExists() {
        boolean isExist = false;
        try {
            int msgCount = deliverBMapper.checkTableForMessage();
            int logCount = deliverBMapper.checkTableForLog();
            if (msgCount >= 0 && logCount >= 0) {
                isExist = true;
            }
        } catch (Exception e) {
            log.error("Check table exists error : {}", e);
        }

        return isExist;
    }
    public List<MunjaonMsg> selectToDeliver(String msgType) {
        return deliverBMapper.selectToDeliver(msgType);
    }
    public int updateToDeliver(String msgId) {
        return deliverBMapper.updateToDeliver(msgId);
    }
    public int updateDeliverForList(List<String> msgIdList) {
        return deliverBMapper.updateDeliverForList(msgIdList);
    }
    public int updateToReport(MunjaonMsg params) {
        return deliverBMapper.updateToReport(params);
    }
    public List<MunjaonMsg> selectToMove() {
        return deliverBMapper.selectToMove();
    }
    public List<MunjaonMsg> selectToExpire(String expireTime) {
        return deliverBMapper.selectToExpire(expireTime);
    }
    public int insertToLog(String msgId) {
        return deliverBMapper.insertToLog(msgId);
    }
    public int deleteFromDeliver(String msgId) {
        return deliverBMapper.deleteFromDeliver(msgId);
    }

    @Transactional
    public void moveToDeliver() {
        List<MunjaonMsg> list = selectToMove();
        if (list == null || list.size() == 0) {
            return;
        }
        log.debug("[CLASS : {} : MOVE_COUNT : {}", this.getClass(), list.size());
        for (MunjaonMsg msg : list) {
            insertToLog(msg.getMsgId());
            deleteFromDeliver(msg.getMsgId());
        }
    }
}
