import assert from "node:assert/strict";
import { test } from 'vitest';
import { SubagentBackgroundJobManager } from "../background-jobs.ts";

test("background job manager stores completed results", async () => {
	const manager = new SubagentBackgroundJobManager<{
		mode: "single";
		results: [];
	}>({
		evictionMs: 60_000,
	});

	const id = manager.register("demo", async () => ({
		content: [{ type: "text", text: "ok" }],
		details: { mode: "single", results: [] },
	}));

	await manager.getJob(id)?.promise;
	const job = manager.getJob(id);
	assert.equal(job?.status, "completed");
	assert.equal(job?.result?.content[0]?.type, "text");
	if (job?.result?.content[0]?.type === "text") {
		assert.equal(job.result.content[0].text, "ok");
	}
	manager.shutdown();
});

test("background job manager cancels running jobs", async () => {
	const manager = new SubagentBackgroundJobManager({
		evictionMs: 60_000,
	});

	const id = manager.register("long", async (signal) => {
		await new Promise<void>((resolve, reject) => {
			const timer = setTimeout(resolve, 10_000);
			signal.addEventListener(
				"abort",
				() => {
					clearTimeout(timer);
					reject(new Error("aborted"));
				},
				{ once: true },
			);
		});
		return { content: [{ type: "text", text: "done" }], details: undefined };
	});

	assert.equal(manager.cancel(id), "cancelled");
	await manager.getJob(id)?.promise;
	assert.equal(manager.getJob(id)?.status, "cancelled");
	manager.shutdown();
});
