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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.msgpush.framework.common.util.object.PageUtils;
import com.njcn.msgpush.module.push.controller.admin.channel.vo.ChannelProviderConfigReqVO;
import com.njcn.msgpush.module.push.dal.dataobject.channel.ChannelProviderConfigDO;
import com.njcn.msgpush.module.push.dal.mysql.channel.ChannelProviderConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChannelProviderConfigServiceImpl extends ServiceImpl<ChannelProviderConfigMapper, ChannelProviderConfigDO> implements ChannelProviderConfigService {

    @Override
    public Page<ChannelProviderConfigDO> getPage(ChannelProviderConfigReqVO reqVO) {
        QueryWrapper<ChannelProviderConfigDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ChannelProviderConfigDO::getChannel, reqVO.getChannel());
        return this.page(new Page<>(PageUtils.getPageNum(reqVO), PageUtils.getPageSize(reqVO)), wrapper);
    }

    @Override
    public List<ChannelProviderConfigDO> getActiveProviders() {
        return this.lambdaQuery().eq(ChannelProviderConfigDO::getEnabled, true).list();
    }

    @Override
    public ChannelProviderConfigDO toggleEnableField(String id) {
        ChannelProviderConfigDO channelProviderConfigDO = this.getById(id);
        channelProviderConfigDO.setEnabled(channelProviderConfigDO.getEnabled() ^ 0X0001);
        return channelProviderConfigDO;
    }

    @Override
    public ChannelProviderConfigDO getByTypeAndChannel(String providerType, String channel) {
        return this.lambdaQuery().eq(ChannelProviderConfigDO::getProviderType, providerType)
                .eq(ChannelProviderConfigDO::getChannel, channel)
                .one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void failureUpdate(String providerType, String channel) {
        ChannelProviderConfigDO byTypeAndChannel = this.getByTypeAndChannel(providerType, channel);
        byTypeAndChannel.setFailureCount(byTypeAndChannel.getFailureCount() + 1);
        byTypeAndChannel.setLastFailureTime(LocalDateTime.now());
        byTypeAndChannel.setHealthStatus(byTypeAndChannel.getFailureCount() > 5 ? 0 : 1);
        this.updateById(byTypeAndChannel);
    }
}
