package com.crm.ucard.configuration;

import com.crm.rely.backend.core.constant.ConfigConstants;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.AESUtil;
import com.crm.ucard.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author gao
 * @date 2026/1/12
 */
@Component
public class CryptoKeyHolder {

    @Value("${card.rsa.private-key-encrypted}")
    private String encryptedPrivateKey;

    private String privateKey;

    @Value("${card.rsa.public-key}")
    private String publicKey;

    @Autowired
    private SysConfigService sysConfigService;

    @PostConstruct
    public void init() {
        try {
            // 1. 启动时加载 AES Key
            String aesKey = getPropertyKey();

            if (aesKey == null) {
                throw new IllegalStateException("AES Key 未配置，系统拒绝启动");
            }

            // 2. 解密 RSA 私钥
            this.privateKey = AESUtil.decrypt(encryptedPrivateKey, aesKey);

        } catch (Exception e) {
            // 强制失败
            throw new RuntimeException("密钥初始化失败，系统启动中断", e);
        }
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public String getPublicKey() {
        return publicKey;
    }

    private String getPropertyKey() throws ServiceException {
        SysConfigTable table = sysConfigService.getByCode(ConfigConstants.FINANCE_PROPERTY_KEY);
        if (table == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return table.getValue();
    }

}
