package com.ga.common.util;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

/**
 * AES-256 CBC 암호화 (resident_no, account_no 등에 사용).
 * 키는 application.yml: ga.encrypt.key (32바이트)
 */
@Component
public class EncryptUtil {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";

    private final byte[] keyBytes;
    private final byte[] iv;

    public EncryptUtil(@Value("${ga.encrypt.key}") String key) {
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        // 키를 32바이트로 정규화
        this.keyBytes = new byte[32];
        for (int i = 0; i < 32; i++) {
            keyBytes[i] = i < raw.length ? raw[i] : (byte) 0;
        }
        // IV는 키의 앞 16바이트 (운영에서는 별도 관리 권장)
        this.iv = new byte[16];
        System.arraycopy(keyBytes, 0, this.iv, 0, 16);
    }

    public String encrypt(String plainText) {
        if (plainText == null || plainText.isEmpty()) return plainText;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, AES), new IvParameterSpec(iv));
            byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, "암호화 실패");
        }
    }

    public String decrypt(String encryptedBase64) {
        if (encryptedBase64 == null || encryptedBase64.isEmpty()) return encryptedBase64;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, AES), new IvParameterSpec(iv));
            byte[] decoded = Base64.getDecoder().decode(encryptedBase64);
            return new String(cipher.doFinal(decoded), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, "복호화 실패");
        }
    }
}
