package com.backendsys.modules.common.interceptor;

import com.backendsys.modules.common.config.security.utils.HttpRequestUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;

/**
 * [拦截器] API日志
 */
@Component
public class ApiLogInterceptor implements HandlerInterceptor {

    @Autowired
    private HttpRequestUtil httpRequestUtil;
    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 记录请求时间
        startTimeThreadLocal.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        // 记录用户ID (如果有的话)
        String userIdLog = "";
        Long user_id = httpRequestUtil.getUserId();
        if (user_id != null) userIdLog = "(user_id: " + user_id + ") ";

        // 请求处理时间
        long consumeTime = System.currentTimeMillis() - startTimeThreadLocal.get();

        // 过滤路径
        List<String> filterPath = Arrays.asList(
            "/js/*",
            "/css/*",
            "/images/*"
        );
        if (filterPath.stream().noneMatch(path -> request.getRequestURI().startsWith(path.replace("*", "")))) {
            System.out.println(
                response.getStatus() + " [" + request.getMethod() + "] " +
                request.getRequestURI() + " (IP: " + httpRequestUtil.getIpAddr() + ") " + userIdLog +
                "Processing Time: " + consumeTime + " ms"
            );
        }
    }
}
