/**
 * E2EE crypto utilities using the native Web Crypto API.
 * This is used to generate temporary RSA key pairs so the backend can
 * securely encrypt vault passwords directly to the client browser in memory.
 */

// Format SPKI key to PEM format string
function spkiToPEM(spkiBuffer: ArrayBuffer): string {
  let binary = '';
  const bytes = new Uint8Array(spkiBuffer);
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  const base64 = window.btoa(binary);
  const formattedB64 = base64.match(/.{1,64}/g)?.join('\n') || '';
  return `-----BEGIN PUBLIC KEY-----\n${formattedB64}\n-----END PUBLIC KEY-----`;
}

export async function generateRSAKeyPair() {
  const keyPair = await window.crypto.subtle.generateKey(
    {
      name: 'RSA-OAEP',
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]), // 65537
      hash: 'SHA-256',
    },
    true, // extractable
    ['encrypt', 'decrypt']
  );

  return keyPair;
}

export async function exportPublicKeyPEM(publicKey: CryptoKey): Promise<string> {
  const spki = await window.crypto.subtle.exportKey('spki', publicKey);
  return spkiToPEM(spki);
}

export async function decryptWithPrivateKey(
  privateKey: CryptoKey,
  encryptedBase64: string
): Promise<string> {
  // Convert base64 to ArrayBuffer
  const binaryString = window.atob(encryptedBase64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  // Decrypt
  const decryptedBuffer = await window.crypto.subtle.decrypt(
    { name: 'RSA-OAEP' },
    privateKey,
    bytes
  );

  // Decode UTF-8
  const decoder = new TextDecoder();
  return decoder.decode(decryptedBuffer);
}
 