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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.msgpush.module.push.constant.MsgStatusConstant;
import com.njcn.msgpush.module.push.dal.dataobject.message.MessageRecordDO;
import com.njcn.msgpush.module.push.dal.dataobject.quota.SystemQuotaConfigDO;
import com.njcn.msgpush.module.push.dal.mysql.quota.SystemQuotaConfigMapper;
import com.njcn.msgpush.module.push.dal.redis.SystemQuotaRedisDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author caozehui
 * @data 2026-03-23
 */
@Service
public class SystemQuotaConfigServiceImpl extends ServiceImpl<SystemQuotaConfigMapper, SystemQuotaConfigDO> implements SystemQuotaConfigService {
    @Autowired
    private SystemQuotaRedisDAO systemQuotaRedisDAO;

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

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

            if (ObjectUtil.isNotNull(systemQuotaConfigDO)) {
                Integer dailyQuota = systemQuotaConfigDO.getDailyQuota();
                Integer count = systemQuotaRedisDAO.get(messageRecordDO.getChannel(), messageRecordDO.getAppName());
                if (count >= dailyQuota) {
                    messageRecordDO.setStatus(MsgStatusConstant.QUOTAEXCEEDED);
                }
            }
        }
    }
}
