package com.erp.alarm;

import com.erp.security.JwtTokenProvider;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class AlarmHandshakeInterceptor implements HandshakeInterceptor {

    private final JwtTokenProvider jwtTokenProvider;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) {
        String token = extractToken(request);
        if (token == null || !jwtTokenProvider.validateToken(token)) {
            log.warn("[WS] handshake rejected: invalid or missing token (uri={})", request.getURI());
            return false;
        }
        try {
            Claims claims = jwtTokenProvider.getClaims(token);
            String userId = claims.get("user_id", String.class);
            String companyCode = claims.get("company_code", String.class);
            if (userId == null) {
                log.warn("[WS] handshake rejected: token has no user_id");
                return false;
            }
            attributes.put("user_id", userId);
            attributes.put("company_code", companyCode);
            log.info("[WS] handshake ok: user={}, company={}", userId, companyCode);
            return true;
        } catch (Exception e) {
            log.warn("[WS] handshake rejected: claims parse failed - {}", e.getMessage());
            return false;
        }
    }

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

    private String extractToken(ServerHttpRequest request) {
        // 브라우저 WebSocket API 는 커스텀 헤더를 못 붙이므로 query string ?token= 우선.
        // 비-브라우저 클라이언트(서버↔서버) 를 위해 Authorization: Bearer 도 fallback 으로 허용.
        if (request instanceof ServletServerHttpRequest sreq) {
            String q = sreq.getServletRequest().getParameter("token");
            if (q != null && !q.isBlank()) return q;
        }
        String auth = request.getHeaders().getFirst("Authorization");
        if (auth != null && auth.startsWith("Bearer ")) {
            return auth.substring(7);
        }
        return null;
    }
}
