package com.moka.gdtauto.resolver;

import com.moka.gdtauto.annotation.AuthUser;
import com.moka.gdtauto.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 认证用户参数解析器
 * 自动将登录拦截器设置的当前用户信息注入到 Controller 方法参数中
 * 
 * @author moka
 * @since 2026-02-09
 */
@Slf4j
@Component
public class AuthUserArgumentResolver implements HandlerMethodArgumentResolver {

    private static final String CURRENT_USER_ATTRIBUTE = "auth-user";

    /**
     * 判断是否支持解析该参数
     * 只有标注了 @AuthUser 注解且参数类型为 SysUser 的参数才会被解析
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 检查参数是否标注了 @AuthUser 注解
        boolean hasAuthUserAnnotation = parameter.hasParameterAnnotation(AuthUser.class);
        // 检查参数类型是否为 SysUser
        boolean isSysUserType = SysUser.class.isAssignableFrom(parameter.getParameterType());
        
        return hasAuthUserAnnotation && isSysUserType;
    }

    /**
     * 解析参数，返回当前登录用户
     * 从请求属性中获取拦截器设置的用户信息
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, 
                                 ModelAndViewContainer mavContainer,
                                 NativeWebRequest webRequest, 
                                 WebDataBinderFactory binderFactory) throws Exception {
        
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            log.warn("无法获取 HttpServletRequest");
            return null;
        }
        
        // 从请求属性中获取当前用户（由 LoginTokenInterceptor 设置）
        SysUser currentUser = (SysUser) request.getAttribute(CURRENT_USER_ATTRIBUTE);
        
        if (currentUser == null) {
            log.warn("未找到当前登录用户信息，URI={}", request.getRequestURI());
            
            // 获取注解的 value 属性（如果有自定义）
            AuthUser authUser = parameter.getParameterAnnotation(AuthUser.class);
            if (authUser != null && !authUser.value().isEmpty()) {
                currentUser = (SysUser) request.getAttribute(authUser.value());
            }
        }
        
        if (currentUser != null) {
            log.debug("成功解析当前登录用户，工号={}", currentUser.getJobNumber());
        }
        
        return currentUser;
    }
}
