package com.ruoyi.websocket.config;

import com.ruoyi.websocket.server.GameRoomWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(gameRoomWebSocketHandler(), "/websocket/{roomId}/{userId}")
                .addInterceptors(new HttpSessionHandshakeInterceptor()) // 添加拦截器
                .setHandshakeHandler(new DefaultHandshakeHandler()) // 设置握手处理器
                .setAllowedOrigins("*"); // 开发环境允许跨域，生产环境应限制
    }

    @Bean
    public GameRoomWebSocketHandler gameRoomWebSocketHandler() {
        return new GameRoomWebSocketHandler();
    }
}