package org.xyzh.common.redis.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 系统配置变更监听器抽象基类
 * 通过Redis Pub/Sub接收配置变更事件，延时2秒后执行刷新（等待事务提交）
 *
 * @author cascade
 * @since 2026-01-01
 */
public abstract class AbstractSysConfigListener implements MessageListener {

    private static final Logger logger = LoggerFactory.getLogger(AbstractSysConfigListener.class);

    /** 延时时间（毫秒），等待事务提交 */
    private static final long DELAY_MILLIS = 2000L;

    /** 调度线程池 */
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
        Thread t = new Thread(r, "sys-config-refresh");
        t.setDaemon(true);
        return t;
    });

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        
        logger.info("收到配置变更事件: channel={}, body={}", channel, body);
        
        // 延时2秒执行，等待发布方事务提交
        scheduler.schedule(() -> {
            try {
                logger.info("开始刷新配置: channel={}", channel);
                doRefresh(channel, body);
                logger.info("配置刷新完成: channel={}", channel);
            } catch (Exception e) {
                logger.error("配置刷新失败: channel={}", channel, e);
            }
        }, DELAY_MILLIS, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行配置刷新，子类实现具体逻辑
     *
     * @param channel 频道名称（对应配置分组）
     * @param body    消息体（可选，可传递额外信息）
     */
    protected abstract void doRefresh(String channel, String body);

    /**
     * 获取监听的频道前缀
     *
     * @return 频道前缀
     */
    public abstract String getChannelPattern();
}
