package com.nanri.aiimage.common.security;

import com.nanri.aiimage.common.exception.BusinessException;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Service
public class ShopCredentialCryptoService {

    @Value("${aiimage.security.shop-credential-key:change-me-shop-credential-key}")
    private String rawKey;

    private SecretKeySpec keySpec;

    @PostConstruct
    public void init() {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] full = sha256.digest(rawKey.getBytes(StandardCharsets.UTF_8));
            byte[] key16 = new byte[16];
            System.arraycopy(full, 0, key16, 0, 16);
            this.keySpec = new SecretKeySpec(key16, "AES");
        } catch (Exception ex) {
            throw new BusinessException("初始化店铺凭据加密器失败");
        }
    }

    public String encrypt(String plainText) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal((plainText == null ? "" : plainText).getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception ex) {
            throw new BusinessException("店铺凭据加密失败");
        }
    }

    public String decrypt(String cipherText) {
        try {
            if (cipherText == null || cipherText.isBlank()) {
                return "";
            }
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            // 兼容历史数据：旧记录可能是明文或使用旧密钥加密，回退原文避免中断自动化流程。
            return cipherText == null ? "" : cipherText;
        }
    }
}
