package com.qiaoba.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.auth.service.AuthConfigApiService;
import com.qiaoba.api.auth.constants.SecurityConstant;
import com.qiaoba.common.base.constant.ConfigConstant;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.common.redis.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 安全配置 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023-05-28 15:09:34
 */
@Service
@RequiredArgsConstructor
public class AuthConfigServiceImpl implements AuthConfigApiService {

    private final RedisService redisService;

    @Override
    public Boolean checkAllowBothOnline() {
        return ConfigConstant.COMMON_ON_VALUE.equals(redisService.get(ConfigConstant.ALLOW_BOTH_ONLINE_KEY));
    }

    @Override
    public Boolean getCaptchaConfig() {
        return ConfigConstant.COMMON_ON_VALUE.equals(redisService.get(ConfigConstant.CAPTCHA_ON_OFF_KEY));
    }

    @Override
    public Boolean getRegisterConfig() {
        return ConfigConstant.COMMON_ON_VALUE.equals(redisService.get(ConfigConstant.REGISTER_ON_OFF_KEY));
    }

    @Override
    public Boolean getBlacklistConfig() {
        return ConfigConstant.COMMON_ON_VALUE.equals(redisService.get(ConfigConstant.BLACKLIST_ON_OFF_KEY));
    }

    @Override
    public Long getBlacklistExpireTime() {
        Object expireTime = redisService.get(ConfigConstant.BLACKLIST_EXPIRE_TIME_KEY);
        return Objects.isNull(expireTime) ? ConfigConstant.DEFAULT_MAX_BLACKLIST_EXPIRE_TIME : Long.parseLong(expireTime.toString());

    }

    @Override
    public Integer getAllowMaxErrorCount() {
        Object count = redisService.get(ConfigConstant.LOGIN_ERROR_MAX_COUNT_KEY);
        return Objects.isNull(count) ? ConfigConstant.DEFAULT_LOGIN_ERROR_MAX_COUNT : Integer.parseInt(count.toString());
    }

    @Override
    public void validateCaptcha(String code, String uuid) {
        if (getCaptchaConfig()) {
            if (StrUtil.isBlank(code) || StrUtil.isBlank(uuid)) {
                throw new ServiceException("验证码或uuid获取失败！");
            }

            String realCode = redisService.getObject(SecurityConstant.CAPTCHA_KEY + uuid, String.class);
            try {
                if (StrUtil.isBlank(realCode)) {
                    throw new ServiceException("验证码已经过期失效！");
                } else {
                    if (!code.equalsIgnoreCase(realCode)) {
                        throw new ServiceException("验证码输入错误！");
                    }
                }

            } finally {
                redisService.del(SecurityConstant.CAPTCHA_KEY + uuid);
            }
        }
    }
}
