package com.test.bijihoudaun.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.bijihoudaun.annotation.RequireCaptcha;
import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.common.response.ResultCode;
import com.test.bijihoudaun.util.CaptchaUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 验证码验证拦截器
 * 拦截标记了 @RequireCaptcha 的方法，验证验证码
 */
@Component
public class CaptchaValidationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 只处理方法请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequireCaptcha requireCaptcha = handlerMethod.getMethodAnnotation(RequireCaptcha.class);

        // 没有注解，不需要验证
        if (requireCaptcha == null) {
            return true;
        }

        // 获取验证码ID和用户输入
        String captchaId = request.getHeader("X-Captcha-Id");
        String captchaCode = request.getHeader("X-Captcha-Code");

        // 检查参数是否存在
        if (captchaId == null || captchaId.isEmpty() || captchaCode == null || captchaCode.isEmpty()) {
            writeErrorResponse(response, "请提供验证码");
            return false;
        }

        // 验证验证码
        if (!CaptchaUtil.validateCaptcha(captchaId, captchaCode)) {
            writeErrorResponse(response, "验证码错误或已过期");
            return false;
        }

        return true;
    }

    /**
     * 写入错误响应
     */
    private void writeErrorResponse(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(400);
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(
                R.fail(ResultCode.FAILED.getCode(), message)
        ));
    }
}
