package com.seer.teach.openapi.cache;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class OpenApiSseLifeCycleCache {

    private static final Duration L2_TTL = Duration.ofMinutes(30);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public Integer get(String prefix, String sn) {
        String key = redisKey(prefix, sn);
        Object raw = redisTemplate.opsForValue().get(key);
        if (raw instanceof Integer) {
            return (Integer) raw;
        }
        return null;
    }

    public void put(String prefix, String sn, Integer value) {
        String key = redisKey(prefix, sn);
        if (value == null) {
            redisTemplate.delete(key);
            return;
        }
        long millis = Optional.ofNullable(L2_TTL).orElse(L2_TTL).toMillis();
        redisTemplate.opsForValue().set(key, value, millis, TimeUnit.MILLISECONDS);
    }

    public void invalidate(String prefix, String sn) {
        redisTemplate.delete(redisKey(prefix, sn));
    }

    public Integer peekL2(String prefix, String sn) {
        return get(prefix, sn);
    }

    private String redisKey(String prefix, String sn) {
        return prefix + sn;
    }
}
