package shop.alien.util.encryption;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import shop.alien.util.encryption.properties.EncryptProperties;

/**
 * Jasypt 自动配置类 - 只要依赖 alien-util 即可自动生效
 */
@Configuration
@EnableConfigurationProperties(EncryptProperties.class)
public class JasyptAutoConfiguration {

    public static final String ALGORITHM = "PBEWithMD5AndDES";

    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor(org.springframework.core.env.Environment environment) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(createConfig(environment));
        return encryptor;
    }

    private SimpleStringPBEConfig createConfig(org.springframework.core.env.Environment environment) {
        // 1. 尝试从 Spring 环境获取（支持 -D 参数和环境变量）
        String pwd = environment.getProperty("jasypt.encryptor.password");

        // 2. 兜底：直接从 OS 环境变量读取（Docker 常用）
        if (pwd == null || pwd.isEmpty()) {
            pwd = System.getenv("JASYPT_ENCRYPTOR_PASSWORD");
        }

        // 3. 兜底：尝试读取系统属性
        if (pwd == null || pwd.isEmpty()) {
            pwd = System.getProperty("jasypt.encryptor.password");
        }

        if (pwd == null || pwd.isEmpty()) {
            // 这里抛出明确异常，防止 Jasypt 报那个模糊的 "empty" 错误
            throw new RuntimeException("Jasypt 密码配置失败！请检查 Docker 环境变量 JASYPT_ENCRYPTOR_PASSWORD 是否正确设置。");
        }

        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(pwd);
        config.setAlgorithm(ALGORITHM);
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
        config.setStringOutputType("base64");
        return config;
    }
}