package ru.micord.ervu.account_applications.security.service;

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.micord.ervu.account_applications.security.exception.EncryptionException;

/**
 * @author Adel Kalimullin
 */
@Component
public class EncryptionService {
  private static final String ALGORITHM = "AES";
  @Value("${ervu.pwd.sign.secret_key}")
  private String secretKey;
  private SecretKeySpec secretKeySpec;

  @PostConstruct
  public void init() {
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      byte[] hash = digest.digest(secretKey.getBytes(StandardCharsets.UTF_8));
      secretKeySpec = new SecretKeySpec(hash, ALGORITHM);
    } catch (Exception e) {
      throw new EncryptionException("Ошибка инициализации ключа", e);
    }
  }

  public String encrypt(String data) {
    try {
      Cipher cipher = Cipher.getInstance(ALGORITHM);
      cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
      byte[] encryptedBytes = cipher.doFinal(data.getBytes());
      return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    catch (Exception e) {
      throw new EncryptionException("Ошибка шифрования данных", e);
    }
  }

  public String decrypt(String encryptedData) {
    try {
      Cipher cipher = Cipher.getInstance(ALGORITHM);
      cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
      byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
      return new String(decryptedBytes);
    }
    catch (Exception e) {
      throw new EncryptionException("Ошибка расшифровки данных", e);
    }
  }
}
