package com.yushu.web.websocket;

import com.yushu.common.core.domain.model.LoginUser;
import com.yushu.common.utils.StringUtils;
import com.yushu.common.utils.spring.SpringUtils;
import com.yushu.framework.web.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * WebSocket握手配置器
 * 负责在握手阶段进行用户身份验证
 */
public class MessageWebSocketConfigurator extends ServerEndpointConfig.Configurator {
    
    private static final Logger log = LoggerFactory.getLogger(MessageWebSocketConfigurator.class);
    
    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        try {
            log.info("[WebSocket] 开始握手处理，URI: {}", request.getRequestURI());
            
            // 从查询参数或Header中获取token
            String token = extractToken(request);
            
            log.info("[WebSocket] 提取到token: {}", token != null ? "存在" : "不存在");
            
            if (StringUtils.isEmpty(token)) {
                log.error("[WebSocket] 握手失败：未提供token");
                return;
            }
            
            // 验证token并获取用户信息
            TokenService tokenService = SpringUtils.getBean(TokenService.class);
            LoginUser loginUser = tokenService.getLoginUser(token);
            
            if (loginUser == null) {
                log.error("[WebSocket] 握手失败：token无效或已过期，token: {}", token);
                return;
            }
            
            // 将用户信息存储到配置中，供后续使用
            config.getUserProperties().put("loginUser", loginUser);
            
            log.info("[WebSocket] 握手成功：用户 {} ({})", loginUser.getUsername(), loginUser.getUserId());
            
        } catch (Exception e) {
            log.error("[WebSocket] 握手异常", e);
        }
    }
    
    /**
     * 从请求中提取token
     */
    private String extractToken(HandshakeRequest request) {
        // 1. 尝试从查询参数获取
        Map<String, List<String>> params = request.getParameterMap();
        if (params.containsKey("token")) {
            List<String> tokens = params.get("token");
            if (!tokens.isEmpty()) {
                return tokens.get(0);
            }
        }
        
        // 2. 尝试从Authorization参数获取
        if (params.containsKey("Authorization")) {
            List<String> auths = params.get("Authorization");
            if (!auths.isEmpty()) {
                return auths.get(0);
            }
        }
        
        // 3. 尝试从Header获取
        Map<String, List<String>> headers = request.getHeaders();
        if (headers.containsKey("Authorization")) {
            List<String> auths = headers.get("Authorization");
            if (!auths.isEmpty()) {
                return auths.get(0);
            }
        }
        
        // 4. 尝试从自定义Header获取
        if (headers.containsKey("Admin-Token")) {
            List<String> tokens = headers.get("Admin-Token");
            if (!tokens.isEmpty()) {
                return tokens.get(0);
            }
        }
        
        return null;
    }
}
