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

import cn.reghao.tnb.account.api.dto.AccountInfo;
import cn.reghao.tnb.account.app.security.form.AccountAuthToken;
import cn.reghao.tnb.account.app.service.AccountTokenService;
import cn.reghao.tnb.account.app.db.mapper.UserAccountMapper;
import cn.reghao.jutil.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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    public AccountInterceptor(UserAccountMapper userAccountMapper, AccountTokenService accountTokenService) {
        this.userAccountMapper = userAccountMapper;
        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.getAuthedToken();
        if (authToken != null) {
            long userId = authToken.getUserId();
            AccountInfo accountInfo = userAccountMapper.findAccountInfo(userId);
            ServletUtil.getSession().setAttribute("profile", accountInfo);
        } else {
            ServletUtil.getSession().setAttribute("profile", null);
        }
    }

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