package top.tqx.demo_1.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.tqx.demo_1.annotation.RequiresPermission;
import top.tqx.demo_1.entity.User;
import top.tqx.demo_1.exception.PermissionDeniedException;
import top.tqx.demo_1.service.AuthService;
import top.tqx.demo_1.service.PermissionService;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod method = (HandlerMethod) handler;

        // 获取当前用户（从 Token 中）
        User currentUser = getCurrentUser(request);
        if (currentUser == null) {
            throw new PermissionDeniedException("用户未登录");
        }

        // 获取请求的权限码
        RequiresPermission annotation = method.getMethodAnnotation(RequiresPermission.class);
        if (annotation != null) {
            String permissionCode = annotation.value();

            // 检查权限
            if (!permissionService.hasPermission(currentUser.getId(), permissionCode)) {
                throw new PermissionDeniedException("无权限访问：" + permissionCode);
            }
        }

        return true;
    }

    private User getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }
        
        return authService.validateToken(token.substring(7));
    }
}
