package cn.reghao.tnb.auth.app.config.web;

import cn.reghao.tnb.auth.app.security.form.AccountAuthToken;
import cn.reghao.tnb.auth.app.service.AccountTokenService;
import cn.reghao.tnb.common.web.ServletUtil;
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;

/**
 * 用户访问日志拦截器
 *
 * @author reghao
 * @date 2023-07-31 10:19:07
 */
@Slf4j
@Component
public class AccountInterceptor implements HandlerInterceptor {
    private final AccountTokenService accountTokenService;

    public AccountInterceptor(AccountTokenService accountTokenService) {
        this.accountTokenService = accountTokenService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {

        AccountAuthToken authToken = accountTokenService.getAuthToken();
        if (authToken != null) {
            long userId = authToken.getUserId();
            ServletUtil.getSession().setAttribute("userId", userId);
        }
    }

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