/* (C) 2024 YiRing, Inc. */
package com.yiring.auth.core;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.yiring.auth.vo.auth.CaptchaVo;
import com.yiring.common.core.Redis;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author Jim
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Captcha {

    final Redis redis;

    static final String CAPTCHA_KEY_PREFIX = "CAPTCHA:";

    /**
     * 生成验证码
     *
     * @return CaptchaVo 验证码信息
     */
    public CaptchaVo create() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 80);
        String key = IdUtil.fastSimpleUUID();
        int expire = 300;
        CaptchaVo vo = CaptchaVo
            .builder()
            .key(key)
            .data("data:image/jpg;base64," + lineCaptcha.getImageBase64())
            .expire(LocalDateTime.now().plusSeconds(expire))
            .build();
        redis.set(CAPTCHA_KEY_PREFIX + key, lineCaptcha.getCode(), expire);
        return vo;
    }

    /**
     * 校验验证码
     *
     * @param key  验证码标识
     * @param code 验证码识别结果
     * @return true: 验证通过 false: 验证失败
     */
    public boolean verify(String key, String code) {
        if (StrUtil.isBlank(key) || StrUtil.isBlank(code)) {
            return false;
        }

        String cacheKey = CAPTCHA_KEY_PREFIX + key;
        String value = redis.get(cacheKey, String.class);
        if (value == null || !value.equals(code)) {
            return false;
        }

        redis.del(cacheKey);
        return true;
    }
}
