package cd.casic.module.terminal.service.impl;

import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.pojo.CommonResult;
import cd.casic.framework.security.core.LoginUser;
import cd.casic.framework.security.core.util.SecurityFrameworkUtils;
import cd.casic.module.terminal.controller.dto.TerminalAccessDTO;
import cd.casic.module.terminal.controller.dto.TerminalConnectDTO;
import cd.casic.module.terminal.controller.dto.TerminalTransferDTO;
import cd.casic.module.terminal.dal.redis.TerminalRedisDAO;
import cd.casic.module.terminal.define.cache.TerminalCacheKeyDefine;
import cd.casic.module.terminal.enums.HostTypeEnum;
import cd.casic.module.terminal.enums.TerminalConnectTypeEnum;
import cd.casic.module.terminal.host.jsch.SessionMessage;
import cd.casic.module.terminal.host.jsch.SessionStores;
import cd.casic.module.terminal.service.HostConnectService;
import cn.orionsec.kit.lang.id.UUIds;

import static cd.casic.framework.commons.pojo.CommonResult.error;
import static cd.casic.framework.commons.pojo.CommonResult.success;
import cn.orionsec.kit.lang.utils.Strings;
import cn.orionsec.kit.lang.utils.Valid;
import cn.orionsec.kit.lang.utils.io.Streams;
import cn.orionsec.kit.net.host.SessionStore;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
 * 终端连接服务
 *
 */
@Slf4j
@Service
public class TerminalService{


    @Resource
    private TerminalRedisDAO terminalRedisDAO;

    @Resource
    private HostConnectService hostConnectService;

    public String getTerminalAccessToken() {
        LoginUser user = Valid.notNull(SecurityFrameworkUtils.getLoginUser());
        log.info("HostTerminalService.getTerminalAccessToken userId: {}", user.getId());
        String accessToken = UUIds.random19();
        TerminalAccessDTO access = TerminalAccessDTO.builder()
                .userId(user.getId())
                .username(SecurityFrameworkUtils.getLoginUserNickname())
                .build();
        // 设置 access 缓存
        String key = TerminalCacheKeyDefine.TERMINAL_ACCESS.format(accessToken);
        terminalRedisDAO.setJson(key, TerminalCacheKeyDefine.TERMINAL_ACCESS, access);
        return accessToken;
    }

    public String getTerminalTransferToken() {

        LoginUser user = Valid.notNull(SecurityFrameworkUtils.getLoginUser());
        log.info("HostTerminalService.getTerminalTransferToken userId: {}", user.getId());
        String transferToken = UUIds.random19();
        TerminalTransferDTO transfer = TerminalTransferDTO.builder()
                .userId(user.getId())
                .username(SecurityFrameworkUtils.getLoginUserNickname())
                .build();
        // 设置 transfer 缓存
        String key = TerminalCacheKeyDefine.TERMINAL_TRANSFER.format(transferToken);
        terminalRedisDAO.setJson(key, TerminalCacheKeyDefine.TERMINAL_TRANSFER, transfer);
        return transferToken;
    }

    public CommonResult testHostConnect(Long id) {
        HostTypeEnum type = HostTypeEnum.of(TerminalConnectTypeEnum.SSH.name());
        if (HostTypeEnum.SSH.equals(type)) {
            // SSH 连接测试
            SessionStore sessionStore = null;
            TerminalConnectDTO info = null;
            try {
                info = hostConnectService.getSshConnectInfo(id);
                sessionStore = SessionStores.openSessionStore(info);
            } catch (Exception e) {
                return error(new ServiceException().setMessage(Strings.format(SessionMessage.SERVER_UNREACHABLE,info.getHostAddress())));
            } finally {
                Streams.close(sessionStore);
            }
        }
        return success();
    }
}
