import { getCryptoBackend } from './backend.js';

// Authenticated encryption using XSalsa20-Poly1305 + X25519 (Curve25519).
// Delegates to the active CryptoBackend (libsodium on desktop, libsodium-rn
// on mobile, etc.).

export interface EncryptedEnvelope {
  ciphertext: Uint8Array;
  nonce: Uint8Array;
}

export async function encryptFor(
  plaintext: Uint8Array,
  recipientPublicKey: Uint8Array,
  senderPrivateKey: Uint8Array,
): Promise<EncryptedEnvelope> {
  const backend = getCryptoBackend();
  const nonce = backend.randomBytes(backend.nonceLength);
  const ciphertext = backend.box(plaintext, nonce, recipientPublicKey, senderPrivateKey);
  return { ciphertext, nonce };
}

export async function decryptFrom(
  ciphertext: Uint8Array,
  nonce: Uint8Array,
  senderPublicKey: Uint8Array,
  recipientPrivateKey: Uint8Array,
): Promise<Uint8Array> {
  const backend = getCryptoBackend();
  return backend.boxOpen(ciphertext, nonce, senderPublicKey, recipientPrivateKey);
}

const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();

export function utf8ToBytes(text: string): Uint8Array {
  return textEncoder.encode(text);
}

export function bytesToUtf8(bytes: Uint8Array): string {
  return textDecoder.decode(bytes);
}
