package gc.mda.signal_batch.global.websocket.listener;

import gc.mda.signal_batch.global.websocket.service.ActiveQueryManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

/**
 * WebSocket 세션 종료 감지 및 진행 중인 쿼리 취소
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WebSocketDisconnectListener {

    private final ActiveQueryManager activeQueryManager;

    /**
     * WebSocket 세션 종료 이벤트 처리
     */
    @EventListener
    public void handleSessionDisconnect(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = headerAccessor.getSessionId();

        if (sessionId == null) {
            return;
        }

        log.info("WebSocket session disconnected: sessionId={}", sessionId);

        // 진행 중인 쿼리가 있으면 취소
        if (activeQueryManager.hasActiveQuery(sessionId)) {
            ActiveQueryManager.ActiveQuery query = activeQueryManager.getQuery(sessionId);

            log.warn("Cancelling active query due to session disconnect: sessionId={}, queryId={}, table={}, processedChunks={}",
                    sessionId,
                    query != null ? query.getQueryId() : "unknown",
                    query != null ? query.getCurrentTable() : "unknown",
                    query != null ? query.getProcessedChunks() : 0);

            activeQueryManager.cancelQuery(sessionId);
            activeQueryManager.completeQuery(sessionId);
        }
    }
}
