package thyyxxk.webserver.config.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
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.controller.ShutDownController;
import thyyxxk.webserver.dao.his.LoginDao;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.service.redislike.RedisLikeService;
import thyyxxk.webserver.utils.StringUtil;

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 final LoginDao dao;

    private static final String EXPIRED = "The Token has expired";

    public AuthenticationInterceptor(LoginDao dao) {
        this.dao = dao;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 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();
        //检查是否有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;
        try {
            code = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            log.error("解析令牌出错！");
            log.info("请求来源：{}", request.getRemoteAddr());
            log.info("请求路径: {}", request.getRequestURI());
            log.info("请求参数: {}", request.getQueryString());
            throw new BizException(ExceptionEnum.TOKEN_ERROR);
        }

        // todo 线上报错这个dao类，连接数据库超时，但是使用了 passtoken的接口是正常返回的
        String password = dao.getPasswordByCode(code);
        if (StringUtil.isBlank(password)) {
            throw new BizException(ExceptionEnum.USER_NOT_EXIST);
        }
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();

        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            if (e.getMessage().contains(EXPIRED)) {
                throw new BizException(ExceptionEnum.TOKEN_EXPIRED);
            } else {
                log.error("验证令牌出错！", e);
                throw new BizException(ExceptionEnum.TOKEN_ERROR);
            }
        }
        return true;
    }
}
