package cn.iocoder.yudao.module.config.service;

import cn.iocoder.yudao.module.config.entity.ReminderMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * Redis 延迟队列服务
 */
@Service
public class RedisDelayedQueueService {

    private static final String REDIS_KEY = "appointment:reminder:queue";

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public void addToQueue(ReminderMessage message, long triggerTimeMillis) {
        try {
            String json = objectMapper.writeValueAsString(message);
            redisTemplate.opsForZSet().add(REDIS_KEY, json, triggerTimeMillis);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to add reminder to Redis", e);
        }
    }

    public Set<String> fetchDueMessages(long currentTimeMillis) {
        return redisTemplate.opsForZSet()
                .rangeByScore(REDIS_KEY, 0, currentTimeMillis);
    }

    public void removeMessage(String json) {
        redisTemplate.opsForZSet().remove(REDIS_KEY, json);
    }
}

