package fr.teamflash.fencerjudgeback.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
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor

const val CHANNEL_MATCH_NAME: String = "/ws/topic/match"

@Configuration
@EnableWebSocketMessageBroker
open class MatchWebSocketConfig : WebSocketMessageBrokerConfigurer {

    override fun configureMessageBroker(registry: MessageBrokerRegistry) {
        // Enable a simple memory-based message broker to send messages to clients
        // Prefix for messages FROM server TO client
        registry.enableSimpleBroker(CHANNEL_MATCH_NAME)
        
        // Prefix for messages FROM client TO server
        registry.setApplicationDestinationPrefixes("/ws")
    }

    override fun registerStompEndpoints(registry: StompEndpointRegistry) {
        // Register the "/ws" endpoint, enabling SockJS fallback options
        registry.addEndpoint("/ws/matches-app")
            .addInterceptors(HttpSessionHandshakeInterceptor())
            .setAllowedOriginPatterns("*") // Allow connections from any origin (adjust for production)
            .withSockJS()
    }
}