package com.loan.system.interceptor;

import com.loan.system.constant.JwtClaimsConstant;
import com.loan.system.context.BaseContext;
import com.loan.system.domain.entity.User;
import com.loan.system.properties.JwtProperties;
import com.loan.system.service.UserService;
import com.loan.system.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
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.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 在拦截的请求前校验jwt
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            BaseContext.setCurrentId(userId);
            setSpringSecurityAuthentication(userId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

    /**
     * 设置Spring Security认证信息
     */
    private void setSpringSecurityAuthentication(Long userId) {
        try {
            // 查询用户信息和权限
            User user = userService.findByIdAndIsDelete(userId);
            if (user == null) {
                log.info("用户不存在: {}", userId);
                return;
            }else{
                log.info("用户信息: {}", user.getId());
            }

            // 获取用户角色并转换为Spring Security权限
            List<GrantedAuthority> authorities = getUserAuthorities(user);

            // 创建认证信息
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(user, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            log.info("Spring Security认证设置完成 - 用户: {}, 角色: {}",
                    user.getUsername(), authorities);
        } catch (Exception e) {
            log.info("设置Spring Security认证信息失败: {}", e.getMessage());
        }
    }

    /**
     * 根据用户信息获取权限列表
     * role字段是逗号分隔的字符串，如 "ADMIN,USER,MANAGER"
     */
    private List<GrantedAuthority> getUserAuthorities(User user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        log.info("用户角色字符串: {}", user.getRole());
        if (user.getRole() != null && !user.getRole().trim().isEmpty()) {
            // 分割逗号分隔的角色字符串
            String[] roleArray = user.getRole().split(",");
            // 为每个角色添加ROLE_前缀并创建权限对象
            for (String role : roleArray) {
                log.info("角色: {}", role);
                String trimmedRole = role.trim();
                if (!trimmedRole.isEmpty()) {
                    authorities.add(new SimpleGrantedAuthority(trimmedRole));
                }
            }
        }
        log.info("用户角色解析: {} -> {}", user.getRole(),
                authorities.stream()
                        .map(GrantedAuthority::getAuthority)
                        .collect(Collectors.toList()));

        return authorities;
    }

}
