package com.example.demo.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.example.demo.service.UserService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 用户活跃时间拦截器
 * 每次用户请求时更新其最后活跃时间，用于统计在线用户数
 */
@Component
public class UserActivityInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(UserActivityInterceptor.class);

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            
            if (authentication != null && authentication.isAuthenticated() 
                && !"anonymousUser".equals(authentication.getPrincipal())) {
                
                String username = authentication.getName();
                
                // 异步更新用户活跃时间，避免阻塞请求
                updateUserActiveTimeAsync(username);
            }
        } catch (Exception e) {
            // 不因活跃时间更新失败而影响正常请求
        }
        
        return true;
    }

    /**
     * 异步更新用户活跃时间
     * 使用专门的方法，不触发缓存清除
     */
    private void updateUserActiveTimeAsync(String username) {
        try {
            userService.updateLastActiveTime(username);
        } catch (Exception e) {
            // 忽略更新失败
        }
    }
}
