package com.njzscloud.common.security.support;


import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.njzscloud.common.core.ex.Exceptions;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class VerificationCodeService {
    private final boolean fixed;

    private final TimedCache<String, String> codeMap = CacheUtil.newTimedCache(1000 * 60 * 5);
    private final TimedCache<String, String> phoneMap = CacheUtil.newTimedCache(1000 * 60);

    public String obtainCode(String phone) {
        if (!fixed) {
            String s = phoneMap.get(phone);
            if (s != null) {
                throw Exceptions.clierr("请勿平繁获取");
            }
        }
        String codeId;
        if (fixed) {
            codeId = "00000";
        } else {
            codeId = IdUtil.simpleUUID();
        }
        phoneMap.put(phone, codeId);
        String code = null;
        if (fixed) {
            code = "00000";
        } else {
            RandomUtil.randomString(5);
        }

        log.info("{} 验证码为：{}", phone, code);
        sendCode(phone, code);
        codeMap.put(codeId, code);
        return codeId;
    }

    public boolean checkCode(String codeId, String code) {
        if (fixed) {
            return true;
        }
        String oldCode = codeMap.get(codeId);
        boolean succ = oldCode != null && oldCode.equals(code);
        if (succ) {
            codeMap.remove(codeId);
        }
        return succ;
    }

    public void sendCode(String phone, String code) {
    }
}
