package com.schisandra.auth.application.utils;

import com.schisandra.auth.common.entity.CaptchaResult;
import com.schisandra.auth.common.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Classname CheckRouteCaptcha
 * @BelongsProject: schisandra-cloud-storage
 * @BelongsPackage: com.schisandra.auth.application.utils
 * @Author: landaiqing
 * @CreateTime: 2024-06-04  21:59
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class CheckRouteCaptcha {
    @Resource
    private RedisUtil redisUtil;
    public final String authRotateCaptchaPrefix = "auth.rotate.captcha";

    public CaptchaResult checkCaptcha(String token, Double deg) {
        if (deg == null && token == null) {
            return CaptchaResult.fail();
        }
        String prefix = redisUtil.buildKey(authRotateCaptchaPrefix, token);
        if (redisUtil.exist(prefix)) {
            double realNum = Double.parseDouble(redisUtil.get(prefix));
            if (Math.abs(realNum - deg) / realNum < 0.05) {
                redisUtil.del(prefix);
                return CaptchaResult.ok();
            } else {
                return CaptchaResult.fail();
            }
        } else {
            return CaptchaResult.fail();
        }

    }
}
