package com.xindazhou.message.config;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.store.RedissonStoreFactory;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

/**
 * SocketIO 配置类
 * 
 * 支持分布式部署：使用 Redis 作为存储后端，实现多服务器节点之间的消息同步
 *
 * @author xindazhou
 */
@Slf4j
@org.springframework.context.annotation.Configuration
public class SocketIOConfig {

    @Value("${socketio.host:0.0.0.0}")
    private String host;

    @Value("${socketio.port:9090}")
    private Integer port;

    @Value("${socketio.max-frame-payload-length:1048576}")
    private int maxFramePayloadLength;

    @Value("${socketio.max-http-content-length:1048576}")
    private int maxHttpContentLength;

    @Value("${socketio.ping-timeout:60000}")
    private int pingTimeout;

    @Value("${socketio.ping-interval:25000}")
    private int pingInterval;

    /**
     * SocketIO 服务器配置
     * 
     * 如果项目中配置了 RedissonClient（通过 redisson-spring-boot-starter），
     * 则自动启用 Redis 存储，实现分布式消息同步
     */
    @Bean
    public SocketIOServer socketIOServer(RedissonClient redissonClient) {
        Configuration config = new Configuration();
        config.setHostname(host);
        config.setPort(port);
        config.setMaxFramePayloadLength(maxFramePayloadLength);
        config.setMaxHttpContentLength(maxHttpContentLength);
        config.setPingTimeout(pingTimeout);
        config.setPingInterval(pingInterval);
        // 允许跨域
        config.setOrigin("*");
        
        // 配置 Redis 存储工厂（实现分布式消息同步）
        // RedissonStoreFactory 是 netty-socketio 官方提供的 Redis 适配器
        config.setStoreFactory(new RedissonStoreFactory(redissonClient));
        log.info("SocketIO Server 已启用 Redis 存储（分布式支持）");
        
        log.info("SocketIO Server 配置完成: host={}, port={}, redis-enabled=true", host, port);
        return new SocketIOServer(config);
    }

}

