package shop.alien.lawyer.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Redis Key過期事件監聽器
 * 
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private final RedisKeyExpirationHandler expirationHandler;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer,
                                      RedisKeyExpirationHandler expirationHandler) {
        super(listenerContainer);
        this.expirationHandler = expirationHandler;
    }

    /**
     * 當Redis key過期時觸發此方法
     * 
     * @param message 過期消息，包含過期的key
     * @param pattern 匹配的模式
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("檢測到Redis Key過期: {}", expiredKey);
        
        try {
            // 處理過期事件
            expirationHandler.handleExpiration(expiredKey);
        } catch (Exception e) {
            log.error("處理Redis Key過期事件失敗, key: {}", expiredKey, e);
        }
    }
}

