package org.dromara.web.service;

import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.exception.user.CaptchaExpireException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.stereotype.Service;

/**
 * 注销账号验证码服务
 */
@RequiredArgsConstructor
@Service
public class AccountCancelCodeService {

    public void validate(String username, String code) {
        String cacheCode = RedisUtils.getCacheObject(buildKey(username));
        if (StringUtils.isBlank(cacheCode)) {
            throw new CaptchaExpireException();
        }
        if (!StringUtils.equals(cacheCode, code)) {
            throw new UserException("验证码无效");
        }
    }

    public void delete(String username) {
        RedisUtils.deleteObject(buildKey(username));
    }

    private String buildKey(String username) {
        return GlobalConstants.CAPTCHA_CODE_KEY + username;
    }

}
