import { describe, it, expect, beforeAll } from 'vitest';
import { encrypt, decrypt } from '@/lib/utils/encryption';

const VALID_KEY = 'a'.repeat(64); // 64 hex chars = 32 bytes

beforeAll(() => {
  process.env.EMAIL_CREDENTIAL_KEY = VALID_KEY;
});

describe('encrypt / decrypt', () => {
  it('round-trips plaintext correctly', () => {
    const plaintext = 'super secret password';
    expect(decrypt(encrypt(plaintext))).toBe(plaintext);
  });

  it('different plaintexts produce different ciphertexts', () => {
    const a = encrypt('hello');
    const b = encrypt('world');
    expect(a).not.toBe(b);
  });

  it('same plaintext produces different ciphertext on each call (random IV)', () => {
    const a = encrypt('hello');
    const b = encrypt('hello');
    expect(a).not.toBe(b);
  });

  it('tampered data field throws on decrypt', () => {
    const stored = JSON.parse(encrypt('tamper me')) as any;
    // Flip the first hex byte of data
    const originalByte = stored.data.slice(0, 2);
    const flipped = originalByte === 'ff' ? '00' : 'ff';
    stored.data = flipped + stored.data.slice(2);

    expect(() => decrypt(JSON.stringify(stored))).toThrow();
  });

  it('tampered auth tag throws on decrypt', () => {
    const stored = JSON.parse(encrypt('tamper tag')) as any;
    const originalByte = stored.tag.slice(0, 2);
    const flipped = originalByte === 'ff' ? '00' : 'ff';
    stored.tag = flipped + stored.tag.slice(2);

    expect(() => decrypt(JSON.stringify(stored))).toThrow();
  });

  it('round-trips an empty string', () => {
    expect(decrypt(encrypt(''))).toBe('');
  });

  it('round-trips unicode text', () => {
    const unicode = '日本語テスト 🚢 αβγ';
    expect(decrypt(encrypt(unicode))).toBe(unicode);
  });

  it('throws when EMAIL_CREDENTIAL_KEY is missing', () => {
    const savedKey = process.env.EMAIL_CREDENTIAL_KEY;
    delete process.env.EMAIL_CREDENTIAL_KEY;

    expect(() => encrypt('test')).toThrow('EMAIL_CREDENTIAL_KEY');

    process.env.EMAIL_CREDENTIAL_KEY = savedKey;
  });

  it('throws when EMAIL_CREDENTIAL_KEY is wrong length', () => {
    const savedKey = process.env.EMAIL_CREDENTIAL_KEY;
    process.env.EMAIL_CREDENTIAL_KEY = 'tooshort';

    expect(() => encrypt('test')).toThrow('EMAIL_CREDENTIAL_KEY');

    process.env.EMAIL_CREDENTIAL_KEY = savedKey;
  });
});
