package com.ssyf.ws.service;

import com.ssyf.ws.constants.WebSocketConstants;
import com.ssyf.ws.domain.SessionInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 会话服务
 * 管理用户WebSocket会话信息
 */
@Slf4j
@Service
public class SessionService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 保存会话信息
     */
    public void saveSession(SessionInfo sessionInfo) {
        String key = WebSocketConstants.REDIS_USER_SESSION_PREFIX + sessionInfo.getSessionId();
        try {
            redisTemplate.opsForValue().set(key, sessionInfo, WebSocketConstants.HEARTBEAT_TIMEOUT, TimeUnit.MILLISECONDS);
            log.debug("保存会话信息: sessionId={}", sessionInfo.getSessionId());
        } catch (Exception e) {
            log.error("保存会话信息失败: sessionId={}", sessionInfo.getSessionId(), e);
        }
    }

    /**
     * 获取会话信息
     */
    public SessionInfo getSession(String sessionId) {
        String key = WebSocketConstants.REDIS_USER_SESSION_PREFIX + sessionId;
        try {
            return (SessionInfo) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("获取会话信息失败: sessionId={}", sessionId, e);
            return null;
        }
    }

    /**
     * 移除会话信息
     */
    public void removeSession(String sessionId) {
        String key = WebSocketConstants.REDIS_USER_SESSION_PREFIX + sessionId;
        try {
            redisTemplate.delete(key);
            log.debug("移除会话信息: sessionId={}", sessionId);
        } catch (Exception e) {
            log.error("移除会话信息失败: sessionId={}", sessionId, e);
        }
    }

    /**
     * 更新最后活跃时间
     */
    public void updateLastActiveTime(String sessionId) {
        SessionInfo sessionInfo = getSession(sessionId);
        if (sessionInfo != null) {
            sessionInfo.updateLastActiveTime();
            saveSession(sessionInfo);
            log.debug("更新会话活跃时间: sessionId={}", sessionId);
        }
    }
}