import { describe, it, expect, beforeAll } from "vitest";
import { encrypt, decrypt } from "@/lib/crypto/aes";

beforeAll(() => {
  process.env.PM_ENCRYPTION_KEY = "0".repeat(64);
});

describe("aes-256-gcm", () => {
  it("roundtrips a string", () => {
    const enc = encrypt("hello world");
    expect(enc).not.toBe("hello world");
    expect(decrypt(enc)).toBe("hello world");
  });

  it("two encrypts of the same plaintext differ (random IV)", () => {
    expect(encrypt("x")).not.toBe(encrypt("x"));
  });

  it("decrypt fails on tampered ciphertext", () => {
    const enc = encrypt("secret-plaintext-long-enough-for-ct-byte-flip");
    // Flip a byte in the middle (skip IV bytes 0-12 and tag bytes 12-28)
    const buf = Buffer.from(enc, "base64");
    buf[40] ^= 0xff;
    const tampered = buf.toString("base64");
    expect(() => decrypt(tampered)).toThrow();
  });

  it("decrypt handles unicode/emoji", () => {
    const txt = "Trường Giang 🚀 password123";
    expect(decrypt(encrypt(txt))).toBe(txt);
  });
});
