package com.schisandra.auth.application.config;

import cn.hutool.core.util.ObjectUtil;
import com.schisandra.auth.application.context.SmsConfigContext;
import com.schisandra.auth.common.redis.RedisUtil;
import com.schisandra.auth.infra.entity.SmsConfigInfo;
import com.schisandra.auth.infra.rpc.SmsConfigRpc;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class SmsInitConfig implements SmartLifecycle {
    @Resource
    SmsReadConfig smsReadConfig;
    @Resource
    SmsConfigRpc smsConfigRpc;

    @Resource
    RedisUtil redisUtil;

    private final String smsConfigPrefix="sys.config";

    public void init() {
        SmsConfigInfo configInfo = smsConfigRpc.getConfigInfo(SmsConfigContext.SMS_CONFIG_KEY);
        if (ObjectUtil.isEmpty(configInfo)){
            log.info("短信配置获取失败！");
        }
        String key = redisUtil.buildKey(smsConfigPrefix, SmsConfigContext.SMS_CONFIG_KEY);
        redisUtil.set(key, configInfo.getConfigValue());
        // 初始化短信配置
        SmsFactory.createSmsBlend(smsReadConfig, configInfo.getConfigValue());
    }

    @Override
    public void start() {
        this.init();
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
