package com.njcn.msgpush.module.push.dal.redis;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class SystemQuotaRedisDAO {
    private final RedisTemplate<String, String> redisTemplate;

    private static final String QUOTA_KEY_PREFIX = "msgPush:quota:";

    private String buildKey(String channel, String appName) {
        return QUOTA_KEY_PREFIX + channel + ":" + appName;
    }

    public void set(String channel, String appName) {
        String key = buildKey(channel, appName);

        long now = System.currentTimeMillis();
        long tomorrowZero = LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long ttl = tomorrowZero - now;
        Boolean absent = redisTemplate.opsForValue().setIfAbsent(key, "1", ttl, TimeUnit.MILLISECONDS);
        if (!absent) {
            Integer oldCount = this.get(channel, appName);
            redisTemplate.opsForValue().set(key, (oldCount + 1) + "", ttl, TimeUnit.MILLISECONDS);
        }
    }

    public Integer get(String channel, String appName) {
        String key = buildKey(channel, appName);
        String countStr = redisTemplate.opsForValue().get(key);
        return ObjectUtil.isNull(countStr) ? 0 : Integer.parseInt(countStr);
    }

}
