package com.oguerreiro.resilient.security;

import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class CrypterUtils {
  private static final String ALGORITHM = "AES";

  public static String AESKeyGenerate() throws NoSuchAlgorithmException {
    KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
    keyGen.init(256); // Use AES-256 for strong security
    SecretKey secretKey = keyGen.generateKey();

    // Encode key as a Base64 string (to store in config)
    String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());

    return encodedKey;
  }

  public static String encrypt(String data, String base64Key) throws Exception {
    byte[] decodedKey = Base64.getDecoder().decode(base64Key);
    SecretKeySpec secretKey = new SecretKeySpec(decodedKey, ALGORITHM);

    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] encryptedBytes = cipher.doFinal(data.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
  }

  public static String decrypt(String encryptedPassword, String secretKey) throws Exception {
    byte[] decodedKey = Base64.getDecoder().decode(secretKey);
    SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM);

    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, key);

    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));
    return new String(decryptedBytes);
  }
}