import { decodeBase64 } from 'jsr:@std/encoding/base64';
import { xchacha20poly1305 } from '@noble/ciphers/chacha';
import { managedNonce } from '@noble/ciphers/webcrypto';
export const encryptionKey = decodeBase64(Deno.env.get('ENCRYPTION_KEY') || '');

/**
 * Encrypts a given Uint8Array using the XChaCha20-Poly1305 algorithm.
 *
 * @param data - The data to be encrypted as a Uint8Array.
 * @param key - The encryption key as a Uint8Array.
 * @returns The encrypted data as a Uint8Array.
 */

export function encryptUint8Array(
  data: Uint8Array,
  key: Uint8Array,
): Uint8Array {
  return managedNonce(xchacha20poly1305)(key).encrypt(data);
}

/**
 * Decrypts a given Uint8Array using the XChaCha20-Poly1305 algorithm.
 *
 * @param data - The data to be decrypted as a Uint8Array.
 * @param key - The decryption key as a Uint8Array.
 * @returns The decrypted data as a Uint8Array.
 */
export function decryptUint8Array(
  data: Uint8Array,
  key: Uint8Array,
): Uint8Array {
  return managedNonce(xchacha20poly1305)(key).decrypt(data);
}