package com.microservices.dss.Interceptor;

import com.microservices.common.core.utils.SpringUtils;
import com.microservices.dss.annotation.GitlinkAdminAccessRequired;
import com.microservices.dss.projects.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import static com.microservices.common.security.auth.AuthUtil.getGitLinkRequestToken;

@Component
public class GitlinkAdminAccessInterceptor implements HandlerInterceptor {

    public UserMapper userMapper = SpringUtils.getBean(UserMapper.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(GitlinkAdminAccessRequired.class)) {
                String token = getGitLinkRequestToken(request);
                Long userId = userMapper.getUserIdByToken(token); // 根据token获取用户ID
                if (userId == null) {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 Forbidden
                    return false;
                }
                Boolean isAdmin = userMapper.getAdminStatus(userId); // 根据用户ID获取admin字段值
                if (isAdmin == null || !isAdmin) {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 Forbidden
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 可以在这里添加一些完成后的处理逻辑
    }
}
