package com.dora.config;

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;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 配置消息代理，用于路由消息
        // /topic 用于公共广播，/queue 用于点对点消息
        config.enableSimpleBroker("/topic", "/queue");
        // 定义客户端发送消息的前缀
        config.setApplicationDestinationPrefixes("/app");
        // 定义点对点消息的用户目标前缀
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册一个STOMP端点，客户端将连接到这个URL
        // 使用 /user 前缀，与其他用户端API保持一致
        // withSockJS()是为不支持WebSocket的浏览器提供的备用选项
        registry.addEndpoint("/user/websocket").setAllowedOriginPatterns("*").withSockJS();
    }
}
