package com.ttstd.signaling.config;

import com.ttstd.signaling.handler.SignalWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final SignalWebSocketHandler signalWebSocketHandler;

    public WebSocketConfig(SignalWebSocketHandler signalWebSocketHandler) {
        this.signalWebSocketHandler = signalWebSocketHandler;
    }

    /**
     * 配置 WebSocket 容器的消息大小限制与会话超时。
     * <p>默认文本消息缓冲区为 8KB，WebRTC SDP（OFFER/ANSWER）消息经 JSON 包装后
     * 可能超过该限制，导致服务端抛出 TextMessageLimitException 并关闭连接。
     * 此处将文本消息上限设为 512KB，二进制消息上限设为 512KB，会话空闲超时设为 10 分钟。
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(512 * 1024);   // 512 KB
        container.setMaxBinaryMessageBufferSize(512 * 1024); // 512 KB
        container.setMaxSessionIdleTimeout(600_000L);        // 10 分钟
        return container;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(signalWebSocketHandler, "/ws/signal")
                .setAllowedOrigins("*");
    }
}
