import { ConfigService } from "@nestjs/config";
import { describe, expect, it, beforeAll } from "vitest";
import { randomBytes } from "node:crypto";
import { EncryptionService } from "./encryption.service";

describe("EncryptionService", () => {
  let service: EncryptionService;

  beforeAll(() => {
    const key = randomBytes(32).toString("base64");
    const config = { get: (k: string) => (k === "MASTER_ENCRYPTION_KEY" ? key : undefined) };
    service = new EncryptionService(config as unknown as ConfigService);
    service.onModuleInit();
  });

  it("round-trips a string", () => {
    const plaintext = "dlocal:secret:abc-123";
    const encrypted = service.encrypt(plaintext);
    expect(encrypted.v).toBe(1);
    expect(encrypted.ciphertext).toBeTruthy();
    expect(service.decrypt(encrypted)).toBe(plaintext);
  });

  it("round-trips JSON", () => {
    const value = { xLogin: "abc", xTransKey: "def", secretKey: "ghi" };
    const encrypted = service.encryptJson(value);
    expect(service.decryptJson(encrypted)).toEqual(value);
  });

  it("rejects tampered ciphertext", () => {
    const encrypted = service.encrypt("hello");
    const tampered = {
      ...encrypted,
      ciphertext: Buffer.from("tampered").toString("base64"),
    };
    expect(() => service.decrypt(tampered)).toThrow();
  });

  it("rejects wrong version", () => {
    expect(() =>
      service.decrypt({
        v: 2 as 1,
        iv: "AAAA",
        authTag: "AAAA",
        ciphertext: "AAAA",
      }),
    ).toThrow();
  });
});
