package com.micer.easyball.filter;

import com.alibaba.fastjson.JSON;
import com.micer.easyball.config.SecurityConfig;
import com.micer.easyball.pojo.LoginUser;
import com.micer.easyball.utils.JwtUtil;
import com.micer.easyball.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        // 1. 检查 Token 是否在黑名单中
        if (redisUtil.hasKey("token_blacklist:" + token)) {
            sendUnauthorized(httpServletResponse, "Token已失效");
            return;
        }

        // 解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();

        } catch (Exception e) {
            sendUnauthorized(httpServletResponse, "token非法");
            return;
        }

        // 从redis中获取用户信息
        String redisKey = "Easyball Login User:" + userId;
        Object o = redisUtil.get(redisKey);

        if (Objects.isNull(o))
        {
            sendUnauthorized(httpServletResponse, "用户未登录");
            return;
        }

        LoginUser loginUser = JSON.parseObject(o.toString(), LoginUser.class);
        // 存入SecurityContextHolder

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void sendUnauthorized(HttpServletResponse response, String msg) throws IOException {
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"status\":401,\"msg\":\"" + msg + "\"}");
    }
}
