package com.ruoyi.loanpricing.service;

import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class SensitiveFieldCryptoService
{
    private final String key;

    public SensitiveFieldCryptoService(@Value("${loan-pricing.sensitive.key:}") String key)
    {
        this.key = key;
    }

    public String encrypt(String plainText)
    {
        validateKey();
        if (!StringUtils.hasText(plainText))
        {
            return plainText;
        }
        try
        {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
            return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)));
        }
        catch (Exception ex)
        {
            throw new ServiceException("贷款定价敏感字段加密失败");
        }
    }

    public String decrypt(String cipherText)
    {
        validateKey();
        if (!StringUtils.hasText(cipherText))
        {
            return cipherText;
        }
        try
        {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
            return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)), StandardCharsets.UTF_8);
        }
        catch (Exception ex)
        {
            throw new ServiceException("贷款定价敏感字段解密失败");
        }
    }

    private void validateKey()
    {
        if (!StringUtils.hasText(key))
        {
            throw new IllegalStateException("loan-pricing.sensitive.key 未配置");
        }
    }
}
