package com.backendsys.modules.common.config.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

// 参考：https://www.jianshu.com/p/bc76da9641a0

@RequiredArgsConstructor
public class CaptchaVerficationFilter extends OncePerRequestFilter {

    private final AntPathRequestMatcher requiresAuthenticationRequestMatcher = new AntPathRequestMatcher("/login", "POST");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(isProtectedUrl(request)) {
            String inputVerifyCode = request.getParameter("code");
            if(!validateVerify(inputVerifyCode)) {
                // 先存入错误 session，在视图访问时再判断是否存在该 session，模拟闪存
                // 从而判断 验证码 与 输入 是否不匹配
                request.getSession().setAttribute("errorVerifyCode", "验证码输入错误");
                response.sendRedirect("/login");
                //
            } else {
                filterChain.doFilter(request,response);
            }
        } else {
            filterChain.doFilter(request,response);
        }
    }


    private boolean validateVerify(String inputVerifyCode) {

        if (inputVerifyCode != null) {

            //获取当前线程绑定的request对象
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            // 这个 code 是在 servlet 中存入 session 的名字
            HttpSession session = request.getSession();
            String verifyCode = (String) session.getAttribute("captcha");

            // System.out.println("前端输入验证码: " + inputVerifyCode + ", session验证码: " + verifyCode);
            // log.info("验证码：{}, 用户输入：{}", validateCode, inputVerify);
            return verifyCode.toLowerCase().equals(inputVerifyCode.toLowerCase());
        } else {
            return false;
        }
    }

    /**
     * 拦截登陆请求
     */
    private boolean isProtectedUrl(HttpServletRequest request) {
        return "POST".equals(request.getMethod()) &&
            requiresAuthenticationRequestMatcher.matches(request);
    }

}
