import { describe, expect, it } from "vitest";
import { hashPayload, normalizePayload } from "./events";

describe("normalizePayload / hashPayload", () => {
  it("produces the same canonical form (and hash) for the same payload regardless of key order and whitespace", async () => {
    const a = normalizePayload('{"b":1,"a":{"y":2,"x":1},"list":[{"k":1,"j":2}]}');
    const b = normalizePayload('{ "a": { "x": 1, "y": 2 }, "list": [ {"j": 2, "k": 1} ], "b": 1 }');

    expect(a.raw).toBe(b.raw);
    expect(await hashPayload(a.raw)).toBe(await hashPayload(b.raw));
  });

  it("canonicalizes an object payload identically to its serialized form", () => {
    const fromObject = normalizePayload({ b: 1, a: "x" });
    const fromString = normalizePayload('{"a":"x","b":1}');

    expect(fromObject.raw).toBe(fromString.raw);
    expect(fromObject.parsed).toEqual({ a: "x", b: 1 });
  });

  it("preserves array element order while sorting object keys", () => {
    const { raw } = normalizePayload('{"items":[3,1,2]}');
    expect(raw).toBe('{"items":[3,1,2]}');
  });

  it("returns parsed=null (raw verbatim) for an unparseable payload string", () => {
    const { raw, parsed } = normalizePayload("not json {");
    expect(parsed).toBeNull();
    expect(raw).toBe("not json {");
  });
});
