package com.walkguide.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;

/**
 * Konfigurasi WebSocket dengan STOMP protocol.
 *
 * TOPIC vs QUEUE:
 *   /topic/... → publish-subscribe (banyak subscriber, 1 publisher)
 *   /queue/... → point-to-point (1 subscriber, 1 publisher)
 *
 * Topics yang digunakan:
 *   Guardian subscribe: /topic/location/{userId}       ← live GPS user
 *   Guardian subscribe: /queue/sos/{guardianId}        ← SOS alert
 *   User subscribe:     /queue/notif/{userId}          ← notifikasi real-time
 *
 * Flutter (stomp_dart_client) connect ke: ws://{host}:{port}/ws
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // Prefix untuk topic/queue yang bisa di-subscribe client
        registry.enableSimpleBroker("/topic", "/queue");

        // Prefix untuk pesan yang dikirim dari client ke server (App destination)
        // Flutter kirim ke /app/location → di-handle @MessageMapping("/location")
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // Endpoint WebSocket utama
        // Flutter connect ke: ws://host:port/ws (tanpa SockJS)
        // Browser/Postman bisa pakai SockJS fallback: http://host:port/ws
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*") // Allow semua origin untuk testing HP di LAN
                .withSockJS();                  // SockJS fallback untuk browser compatibility
    }
}
