import { describe, it, expect } from 'bun:test';
import { generateKey, encrypt, decrypt, deriveKey } from './crypto';

describe('crypto', () => {
  it('encrypts and decrypts data round-trip', async () => {
    const key = await generateKey();
    const plaintext = JSON.stringify({ hello: 'world' });

    const { ciphertext, iv } = await encrypt(key, plaintext);
    const decrypted = await decrypt(key, ciphertext, iv);

    expect(JSON.parse(decrypted)).toEqual({ hello: 'world' });
  });

  it('produces different ciphertexts for same plaintext', async () => {
    const key = await generateKey();
    const plaintext = 'test';

    const a = await encrypt(key, plaintext);
    const b = await encrypt(key, plaintext);

    expect(a.ciphertext).not.toEqual(b.ciphertext); // unique IV per encryption
  });

  it('derives consistent keys from the same passphrase', async () => {
    const k1 = await deriveKey('secret password', 'salt123');
    const k2 = await deriveKey('secret password', 'salt123');
    // Both should encrypt/decrypt interchangeably
    const { ciphertext, iv } = await encrypt(k1, 'data');
    const result = await decrypt(k2, ciphertext, iv);
    expect(result).toBe('data');
  });
});
