package com.m2pool.chat.interceptor;

import com.m2pool.common.core.utils.ip.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.m2pool.chat.constant.CustomHeader.IPADDR;


/**
 * @ClassName WebsocketHandshakeInterceptor
 * @Description websocket 握手处理器类 适用于前端原生websocket实现.建立websocket链接时调用
 * @Author yyb
 * @Date 2025/4/10 15:39
 */
public class WebsocketHandshakeInterceptor implements HandshakeInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebsocketHandshakeInterceptor.class);



    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        LOGGER.info("------------------WebsocketHandshakeInterceptor:beforeHandshake");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletRequest.getServletRequest();
            // 获取 客服端 IP 地址 并放入attributes 中
            String ipAddr = IpUtils.getIpAddr(httpRequest);
            attributes.put(IPADDR, ipAddr);
        } else {
            LOGGER.warn("Request is not an instance of ServletServerHttpRequest. Unable to extract HttpServletRequest.");
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        LOGGER.info("------------------WebsocketHandshakeInterceptor:afterHandshake");
    }

}
