package test05.interceptor;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import test05.enums.UserRole;
import test05.pojo.Result;
import test05.utils.JwtUtils;
import test05.utils.UserRoleUtils;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        String token = request.getHeader("token");
        try{
            JwtUtils.parseJwt(token);
            
            // 检查角色权限
            UserRole userRole = UserRoleUtils.getUserRoleFromToken(token);
            if (userRole == null) {
                response.getWriter().print(JSONObject.toJSONString(Result.error("invalid user role")));
                return false;
            }
            
            String requestURI = request.getRequestURI();
            if (!userRole.hasAccessToPath(requestURI)) {
                response.getWriter().print(JSONObject.toJSONString(Result.error("access denied")));
                return false;
            }
            
        }catch(Exception e){
            response.getWriter().print(JSONObject.toJSONString(Result.error("not login")));
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

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

    }
}
