package com.liquidnet.common.third.secureaccess.config;

import cn.anicert.secure.access.config.bean.AccessConfig;
import cn.anicert.secure.access.crypto.service.ISoftCryptoService;
import cn.anicert.secure.access.crypto.service.impl.SoftCryptoServiceImpl;
import cn.anicert.secure.access.utils.ConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Slf4j
@Configuration
public class SecureAccessConfiguration {

    private final SecureAccessProperties properties;

    public SecureAccessConfiguration(SecureAccessProperties properties) {
        this.properties = properties;
    }

    @Bean
    public ISoftCryptoService softCryptoService() {
        return new SoftCryptoServiceImpl();
    }

    @PostConstruct
    public void initSecureAccessSdk() {
        if (StringUtils.isAnyBlank(
                properties.getCustomerNo(),
                properties.getAccessUrl(),
                properties.getSignPrivateKey(),
                properties.getSignVerifyPublicKey())) {
            log.warn("[secure-access] 配置不完整，网证认证功能不可用");
            return;
        }
        AccessConfig accessConfig = new AccessConfig();
        accessConfig.setOrgId(properties.getOrgId());
        accessConfig.setCustomerNo(properties.getCustomerNo());
        accessConfig.setAccessUrl(properties.getAccessUrl());
        accessConfig.setSignPrivateKey(properties.getSignPrivateKey());
        accessConfig.setSignVerifyPublicKey(properties.getSignVerifyPublicKey());
        accessConfig.setDataEncryptKey(properties.getDataEncryptKey());
        ConfigUtil.initConfig(accessConfig);
        log.info("[secure-access] SDK 初始化完成, customerNo={}", properties.getCustomerNo());
    }
}
