// components/main/settingsPageComponents/utils/cryptoUtils.ts
import CryptoJS from "crypto-js";

// Generiert den Schlüssel und IV für AES-Verschlüsselung
export function generateKeyAndIV() {
  const encryptionKey = process.env.NEXT_PUBLIC_ENCRYPTION_KEY;
  const encryptionIV = process.env.NEXT_PUBLIC_ENCRYPTION_IV;

  if (!encryptionKey || !encryptionIV) {
    throw new Error("Encryption key or IV is not defined.");
  }

  const key = CryptoJS.enc.Utf8.parse(encryptionKey);
  const iv = CryptoJS.enc.Utf8.parse(encryptionIV);
  return { key, iv };
}

// Generiert einen verschlüsselten Token
export function generateToken(user) {
  const payload = {
    username: user.username,
    role: user.role,
    exp: Date.now() + 5 * 60 * 1000, // Ablaufzeit: 5 Minuten
  };
  const token = JSON.stringify(payload);
  const { key, iv } = generateKeyAndIV();
  return CryptoJS.AES.encrypt(token, key, { iv }).toString();
}
