import { InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as CryptoJS from 'crypto-js';

const configService = new ConfigService

const secretKey = CryptoJS.enc.Utf8.parse(configService.get("CRYPTO_SECRET_KEY"))

if (!secretKey) {
  throw new InternalServerErrorException('Secret key are required')
}

export function encrypt (data) {
  const bytes = CryptoJS.AES.encrypt(data, secretKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString();

  return bytes.toString(CryptoJS.enc.Base64);
}

export function decrypt (encryptedData) {
  try {
    const bytes = CryptoJS.AES.decrypt(encryptedData, secretKey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return bytes.toString(CryptoJS.enc.Utf8);
  } catch (e) {
    return null;
  }
}