package thyyxxk.webserver.config.auth;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.utils.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author dj
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    private boolean isProd = true;

    AuthenticationInterceptor(Boolean isProd) {
        this.isProd = isProd;
    }

    AuthenticationInterceptor() {
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object object) {
        HandlerMethod handlerMethod;
        try {
            handlerMethod = (HandlerMethod) object;
        } catch (Exception e) {
            log.error("无法转换请求，请用正确的方式访问！");
            log.info("请求来源：{}", request.getRemoteAddr());
            log.info("请求路径: {}", request.getRequestURI());
            log.info("请求参数: {}", request.getQueryString());
            throw new BizException(ExceptionEnum.BAD_REQUEST);
        }
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(IsProd.class)) {
            if (!isProd) {
                throw new BizException(ExceptionEnum.TEST_ENVIRONMENT);
            }
        }

        //检查是否有PassToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 执行认证
        String token = request.getHeader("token");
        if (token == null) {
            log.error("没有找到令牌！");
            log.info("请求来源：{}", request.getRemoteAddr());
            log.info("请求路径: {}", request.getRequestURI());
            log.info("请求参数: {}", request.getQueryString());
            throw new BizException(ExceptionEnum.TOKEN_NOT_EXIST);
        }
        // 获取 token 中的 user code
        String code = TokenUtil.getInstance().getTokenUserId(token);
        if (null == code) {
            log.error("解析令牌出错！");
            log.info("请求来源：{}", request.getRemoteAddr());
            log.info("请求路径: {}", request.getRequestURI());
            log.info("请求参数: {}", request.getQueryString());
            throw new BizException(ExceptionEnum.TOKEN_ERROR);
        }
        TokenUtil.getInstance().verifyToken(token);
        return true;
    }
}
