import { describe, test, expect } from 'bun:test';
import { aeadOpen, aeadSeal, AEAD_NONCE_LEN, AEAD_TAG_LEN } from '../src/crypto/aead.js';

const TEXT = new TextEncoder();

describe('AEAD — basic seal/open', () => {
  const key = new Uint8Array(32).fill(0xAA);
  const nonce = new Uint8Array(AEAD_NONCE_LEN).fill(0x55);
  const aad = TEXT.encode('shade-aad-v1|sessions|session|alice');
  const pt = TEXT.encode('hello shade');

  test('round-trips', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    expect(blob.length).toBe(AEAD_NONCE_LEN + pt.length + AEAD_TAG_LEN);
    const opened = await aeadOpen(key, blob, aad);
    expect(opened).toEqual(pt);
  });

  test('blob carries the nonce in the prefix', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    expect(blob.subarray(0, AEAD_NONCE_LEN)).toEqual(nonce);
  });

  test('rejects wrong key', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    const wrong = new Uint8Array(32).fill(0xBB);
    await expect(aeadOpen(wrong, blob, aad)).rejects.toThrow();
  });

  test('rejects wrong AAD', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    await expect(aeadOpen(key, blob, TEXT.encode('different aad'))).rejects.toThrow();
  });

  test('rejects flipped ciphertext bit', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    const tampered = new Uint8Array(blob);
    tampered[AEAD_NONCE_LEN + 2]! ^= 0x01;
    await expect(aeadOpen(key, tampered, aad)).rejects.toThrow();
  });

  test('rejects flipped tag bit', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    const tampered = new Uint8Array(blob);
    tampered[blob.length - 1]! ^= 0x01;
    await expect(aeadOpen(key, tampered, aad)).rejects.toThrow();
  });

  test('rejects flipped nonce bit (mismatch with expected)', async () => {
    const blob = await aeadSeal(key, nonce, pt, aad);
    const tampered = new Uint8Array(blob);
    tampered[1]! ^= 0x01;
    await expect(aeadOpen(key, tampered, aad, nonce)).rejects.toThrow(/nonce mismatch/);
  });

  test('rejects too-short blob', async () => {
    await expect(aeadOpen(key, new Uint8Array(10), aad)).rejects.toThrow();
  });

  test('rejects nonce of wrong size on seal', async () => {
    await expect(aeadSeal(key, new Uint8Array(8), pt, aad)).rejects.toThrow();
  });
});
