package com.snack.server.module.chat.websocket;

import cn.dev33.satoken.stp.StpUtil;
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 java.security.Principal;
import java.util.Map;

/**
 * WebSocket 握手拦截器
 *
 * 客户端连接 ws://host/ws/chat?type=user|admin&token=xxx
 * 通过 Sa-Token 校验 token 并解析出登录身份作为 Principal
 */
public class ChatHandshakeInterceptor implements HandshakeInterceptor {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ChatHandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) {
        if (!(request instanceof ServletServerHttpRequest servletRequest)) {
            log.warn("[ws] 非 Servlet 请求，拒绝");
            return false;
        }

        String query = servletRequest.getServletRequest().getQueryString();
        String token = null;
        String type = "user";

        if (query != null) {
            for (String param : query.split("&")) {
                String[] kv = param.split("=", 2);
                if (kv.length != 2) continue;
                if ("token".equalsIgnoreCase(kv[0])) {
                    token = kv[1];
                } else if ("type".equalsIgnoreCase(kv[0])) {
                    type = kv[1];
                }
            }
        }

        if (token == null || token.isEmpty()) {
            log.warn("[ws] 缺少 token");
            return false;
        }

        try {
            Object loginId = StpUtil.getLoginIdByToken(token);
            if (loginId == null) {
                log.warn("[ws] token 无效: {}", token);
                return false;
            }

            long id = Long.parseLong(loginId.toString());
            boolean isAdmin = "admin".equalsIgnoreCase(type);

            attributes.put("loginId", id);
            attributes.put("loginType", isAdmin ? "admin" : "user");
            log.info("[ws] 握手成功 type={} id={}", type, id);
            return true;

        } catch (Exception e) {
            log.warn("[ws] token 校验异常: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
    }

    public static Principal createPrincipal(Map<String, Object> attributes) {
        Long loginId = (Long) attributes.get("loginId");
        String loginType = (String) attributes.get("loginType");
        if (loginId == null) return null;
        return () -> loginType + ":" + loginId;
    }
}
