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

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.constant.MsgStatusConstant;
import com.njcn.msgpush.module.push.controller.admin.ratelimit.VO.RateLimitConfigReqVO;
import com.njcn.msgpush.module.push.dal.dataobject.message.MessageRecordDO;
import com.njcn.msgpush.module.push.dal.dataobject.ratelimit.RateLimitConfigDO;
import com.njcn.msgpush.module.push.dal.mysql.ratelimit.RateLimitConfigMapper;
import com.njcn.msgpush.module.push.dal.redis.RateLimitRedisDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author caozehui
 * @data 2026-03-13
 */
@Service
public class RateLimitConfigServiceImpl extends ServiceImpl<RateLimitConfigMapper, RateLimitConfigDO> implements RateLimitConfigService {

    @Autowired
    private RateLimitRedisDAO rateLimitRedisDAO;

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


    @Override
    public RateLimitConfigDO getByChannelAndAppName(String channel, String appName) {
        return this.lambdaQuery().eq(RateLimitConfigDO::getChannel, channel)
                .eq(RateLimitConfigDO::getAppName, appName)
                .eq(RateLimitConfigDO::getEnabled, true).one();
    }

    @Override
    public void check(List<MessageRecordDO> messageRecordList) {
        for (int i = 0; i < messageRecordList.size(); i++) {
            MessageRecordDO messageRecordDO = messageRecordList.get(i);
            RateLimitConfigDO rateLimitConfigDO = this.getByChannelAndAppName(messageRecordDO.getChannel(), messageRecordDO.getAppName());

            if (ObjectUtil.isNotNull(rateLimitConfigDO)) {
                Integer dailyQuota = rateLimitConfigDO.getDailyLimit();
                Integer count = rateLimitRedisDAO.get(messageRecordDO.getChannel(), messageRecordDO.getAppName(), messageRecordDO.getReceiver());
                if (count >= dailyQuota) {
                    messageRecordDO.setStatus(MsgStatusConstant.RATE_LIMITED);
                }
            }
        }
    }
}
