package com.mosquito.project.web;

import com.mosquito.project.permission.PermissionCheckService;
import com.mosquito.project.permission.RequirePermission;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 权限校验拦截器
 * 对标注了 @RequirePermission 的方法进行权限校验
 */
public class PermissionInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(PermissionInterceptor.class);

    private final PermissionCheckService permissionCheckService;

    public PermissionInterceptor(PermissionCheckService permissionCheckService) {
        this.permissionCheckService = permissionCheckService;
    }

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

        Method method = handlerMethod.getMethod();
        RequirePermission annotation = method.getAnnotation(RequirePermission.class);

        // 没有标注权限注解，放行
        if (annotation == null) {
            return true;
        }

        // 从请求属性中获取用户ID（在JWT拦截器中设置）
        // 兼容String和Long类型的userId
        Object userIdObj = request.getAttribute("userId");
        Long userId = null;
        if (userIdObj instanceof Long) {
            userId = (Long) userIdObj;
        } else if (userIdObj instanceof String) {
            try {
                userId = Long.parseLong((String) userIdObj);
            } catch (NumberFormatException e) {
                log.warn("权限校验失败: userId格式错误: {}", userIdObj);
            }
        }

        if (userId == null) {
            log.warn("权限校验失败: 无法获取用户ID");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"未登录或token无效\"}");
            return false;
        }

        String requiredPermission = annotation.value();
        boolean hasPermission = permissionCheckService.hasPermission(userId, requiredPermission);

        if (!hasPermission) {
            log.warn("权限不足: userId={}, requiredPermission={}, method={}",
                userId, requiredPermission, method.getName());
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("{\"code\":403,\"message\":\"权限不足: " + requiredPermission + "\"}");
            return false;
        }

        return true;
    }
}
