package cn.sikey.websocket.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.websocket.websocket.Connection;
import lombok.experimental.UtilityClass;
import org.springframework.http.HttpStatus;
import org.springframework.web.socket.WebSocketSession;

import java.time.Instant;
import java.util.Map;
import java.util.Objects;


/**
 * @Author: nelson
 * @Date: 2025/5/29
 * @Description: 连接转换器
 */
@UtilityClass
public class ConnectionConverterUtil {

    /**
     * 转换
     *
     * @param session WebSocketSession
     * @return Connection
     */
    public Connection to(WebSocketSession session) {
        Objects.requireNonNull(session.getUri());
        Map<String, String> request = HttpUtil.decodeParamMap(session.getUri().getQuery(), CharsetUtil.CHARSET_UTF_8);
        String id = request.get("id");

        if (StrUtil.isBlank(id)) {
            throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "id is required");
        }


        String webSocketKey = session.getHandshakeHeaders().get("Sec-WebSocket-Key").getFirst();
        return new Connection()
                .setId(id)
                .setWebsocketKey(webSocketKey)
                .setLastHeartbeat(Instant.now());
    }
}
