package com.qqchen.deploy.backend.framework.ssh.websocket;

import com.qqchen.deploy.backend.framework.enums.SSHTargetType;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SSH会话管理器（Framework层）
 * 管理所有活跃的SSH会话，提供并发控制能力
 */
@Slf4j
@Component
public class SSHSessionManager {
    
    /**
     * 会话信息存储：sessionId -> SSHSessionInfo
     */
    private final Map<String, SSHSessionInfo> sessions = new ConcurrentHashMap<>();
    
    /**
     * 注册会话
     * 
     * @param sessionId WebSocket会话ID
     * @param userId 用户ID
     * @param targetType 目标类型
     * @param targetId 目标ID
     */
    public void registerSession(String sessionId, Long userId, SSHTargetType targetType, Object targetId) {
        SSHSessionInfo info = new SSHSessionInfo();
        info.setSessionId(sessionId);
        info.setUserId(userId);
        info.setTargetType(targetType);
        info.setTargetId(targetId);
        info.setConnectTime(LocalDateTime.now());
        
        sessions.put(sessionId, info);
        log.debug("会话已注册: sessionId={}, userId={}, target={}:{}", 
            sessionId, userId, targetType, targetId);
    }
    
    /**
     * 移除会话
     * 
     * @param sessionId WebSocket会话ID
     */
    public void removeSession(String sessionId) {
        SSHSessionInfo removed = sessions.remove(sessionId);
        if (removed != null) {
            log.debug("会话已移除: sessionId={}, userId={}, target={}:{}", 
                sessionId, removed.getUserId(), removed.getTargetType(), removed.getTargetId());
        }
    }
    
    /**
     * 统计用户对指定目标的活跃会话数
     * 
     * @param userId 用户ID
     * @param targetType 目标类型
     * @param targetId 目标ID
     * @return 活跃会话数
     */
    public long countActiveSessions(Long userId, SSHTargetType targetType, Object targetId) {
        return sessions.values().stream()
            .filter(s -> s.getUserId().equals(userId) 
                && s.getTargetType() == targetType
                && s.getTargetId().equals(targetId))
            .count();
    }
    
    /**
     * 获取会话信息
     * 
     * @param sessionId WebSocket会话ID
     * @return 会话信息
     */
    public SSHSessionInfo getSession(String sessionId) {
        return sessions.get(sessionId);
    }
    
    /**
     * 获取所有活跃会话数
     * 
     * @return 会话总数
     */
    public int getTotalSessions() {
        return sessions.size();
    }
    
    /**
     * SSH会话信息
     */
    @Data
    public static class SSHSessionInfo {
        private String sessionId;
        private Long userId;
        private SSHTargetType targetType;
        private Object targetId;
        private LocalDateTime connectTime;
    }
}
