package top.imwork.window.silos.handler;

import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import top.imwork.commons.core.constants.Constants;
import top.imwork.commons.core.utils.StringUtils;
import top.imwork.window.silos.exception.CaptchaException;
import top.imwork.window.silos.utils.RedisUtils;

import java.io.IOException;

/**
 * Copyright (C), 2015-2026
 * FileName: ValidateCodeFilter
 * Author<作者姓名>:   stars
 * CreateTime<创建时间>:   2026/1/12 17:36
 * UpdateTime<修改时间>:   2026/1/12 17:36
 * Description〈功能简述〉: 验证码校验
 * History<历史描述>:
 * Since<版本号>: 1.0.0
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtils redisUtils;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 只拦截登录请求
        if (antPathMatcher.match("/auth/login", request.getRequestURI())
                && "POST".equalsIgnoreCase(request.getMethod())) {

            try {
                validateCaptcha(request);
                filterChain.doFilter(request, response);
            } catch (CaptchaException e) {
                request.getSession().setAttribute("message", "验证码错误");
                response.sendRedirect("/login.html");
                // 验证码错误，返回错误信息
                /*response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(
                        "{\"code\":500,\"msg\":\"验证码错误\",\"data\":null}"
                );*/
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    private void validateCaptcha(HttpServletRequest request) {
        String captcha = request.getParameter("imageCode");
        Object cacheCode = redisUtils.hget(Constants.SESSION_KEY,request.getSession().getId());
        String captchaCode = (String) cacheCode;

        if (StringUtils.isEmpty(captcha) || StringUtils.isEmpty(cacheCode)) {
            throw new CaptchaException("验证码不能为空");
        }

        if (StringUtils.isEmpty(captchaCode)) {
            throw new CaptchaException("验证码已过期");
        }

        if (!captcha.equalsIgnoreCase(captchaCode)) {
            throw new CaptchaException("验证码错误");
        }

        // 验证成功后删除验证码
        redisUtils.hdel(Constants.SESSION_KEY,request.getSession().getId());
    }
}