package cn.reghao.bnt.web.config;

import cn.reghao.bnt.web.admin.service.*;
import cn.reghao.jutil.jdk.http.HeaderNames;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 用户访问拦截器
 *
 * @author reghao
 * @date 2023-07-31 10:19:07
 */
@Slf4j
@Component
public class AccessInterceptor implements HandlerInterceptor {
    private final LogService logService;

    public AccessInterceptor(LogService logService) {
        this.logService = logService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        request.setAttribute(HeaderNames.XRequestId, requestId);
        long startTime = System.currentTimeMillis();
        request.setAttribute(HeaderNames.XRequestTime, startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //logService.saveAccessLog();
    }

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