// @vitest-environment happy-dom
import { afterEach, describe, expect, it } from "vitest";
import { emit, flushEvents, initEvents, pendingEvents } from "./events.js";

describe("flushEvents", () => {
	afterEach(() => {
		initEvents("", undefined);
	});

	it("envoie la cle publique avec le lot", async () => {
		const blobs: Blob[] = [];
		navigator.sendBeacon = ((_url, data) => {
			if (data instanceof Blob) blobs.push(data);
			return true;
		}) as typeof navigator.sendBeacon;

		initEvents("pk_live", "http://127.0.0.1:8787/v1/events");
		emit({
			type: "start",
			tourId: "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
			tourVersion: 1,
		});
		expect(pendingEvents()).toHaveLength(1);
		flushEvents();
		expect(pendingEvents()).toHaveLength(0);
		const blob = blobs[0];
		expect(blob).toBeDefined();
		if (!blob) return;
		expect(JSON.parse(await blob.text())).toMatchObject({
			key: "pk_live",
			events: [{ type: "start", tourVersion: 1 }],
		});
	});
});
