package com.changhu.support.interceptor;

import cn.hutool.core.util.ArrayUtil;
import com.changhu.common.annotation.CheckUserType;
import com.changhu.common.db.enums.UserType;
import com.changhu.common.exception.MessageException;
import com.changhu.common.utils.UserUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 20252
 * @createTime 2024/9/4 下午4:00
 * @desc UserTypeInterceptor...
 */
public class UserTypeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        if (handler instanceof HandlerMethod handlerMethod) {
            boolean b = false;
            UserType[] uts = null;

            CheckUserType clazzJsonBody = handlerMethod.getBeanType().getAnnotation(CheckUserType.class);
            CheckUserType methodJsonBody = handlerMethod.getMethodAnnotation(CheckUserType.class);

            if (clazzJsonBody != null) {
                if (methodJsonBody == null) {
                    b = true;
                    uts = clazzJsonBody.userTypes();
                } else if (methodJsonBody.value()) {
                    b = true;
                    uts = methodJsonBody.userTypes();
                }
            } else {
                if (methodJsonBody != null && methodJsonBody.value()) {
                    b = true;
                    uts = methodJsonBody.userTypes();
                }
            }

            if (b && ArrayUtil.isNotEmpty(uts)) {
                if (!ArrayUtil.contains(uts, UserUtil.getUserType())) {
                    throw new MessageException("客户端类型不对");
                }
            }
        }
        return true;
    }
}
