package org.xyzh.workcase.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * WebSocket配置类
 * 用于聊天室实时消息推送
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private WebSocketAuthInterceptor webSocketAuthInterceptor;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 配置消息代理
        // 客户端订阅路径前缀：/topic（广播）、/queue（点对点）
        config.enableSimpleBroker("/topic", "/queue");
        
        // 客户端发送消息路径前缀
        config.setApplicationDestinationPrefixes("/app");
        
        // 点对点消息前缀
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 原生WebSocket端点（不使用SockJS）
        registry.addEndpoint("/workcase/ws/chat")
                .setAllowedOriginPatterns("*")
                .addInterceptors(webSocketAuthInterceptor);
        
        // SockJS端点（用于不支持WebSocket的浏览器降级）
        registry.addEndpoint("/workcase/ws/chat-sockjs")
                .setAllowedOriginPatterns("*")
                .addInterceptors(webSocketAuthInterceptor)
                .withSockJS();
    }
}
