package tech.easyflow.common.captcha.tainai;

import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.easyflow.common.util.RequestUtil;
import tech.easyflow.common.util.ResponseUtil;

@Component
public class CaptchaValidInterceptor implements HandlerInterceptor {

    @Resource
    private CaptchaVerificationService captchaVerificationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        JSONObject jsonObject = (JSONObject) RequestUtil.readJsonObjectOrArray(request);
        String validToken = jsonObject.getString("validToken");
        if (!captchaVerificationService.verify(validToken)) {
            renderNotLogin(response);
            return false;
        }
        return true;
    }

    private void renderNotLogin(HttpServletResponse response) {
        ResponseUtil.renderJson(response, captchaVerificationService.failureResult());
    }
}
