package com.snack.server.config;

import com.snack.server.module.chat.websocket.ChatHandshakeInterceptor;
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 STOMP 配置
 *
 * 端点: /ws/chat?token=xxx&type=user|admin
 * 客户端订阅: /user/queue/chat/{sessionId} 收消息
 *             /user/queue/chat/event 收系统事件
 * 客户端发送: /app/chat/send   发消息
 *             /app/chat/ack    已读确认
 *             /app/chat/close  关闭会话
 *             /app/chat/accept 客服接管
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws/chat")
                .setAllowedOriginPatterns("*")
                .addInterceptors(new ChatHandshakeInterceptor())
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 应用消息前缀（客户端发送到 @MessageMapping 的路径）
        registry.setApplicationDestinationPrefixes("/app");
        // 用户专属队列前缀（点对点推送）
        registry.setUserDestinationPrefix("/user");

        // 使用内存 Broker 推送 /topic 和 /queue
        registry.enableSimpleBroker("/topic", "/queue");
    }
}
