import { describe, expect, it, vi } from "vitest";
import * as knot from "./knot";
import { ClientResponseError, createBobbinClient, type BobbinContext } from "./client";

const jsonResponse = (body: unknown, init: ResponseInit = {}): Response =>
	new Response(JSON.stringify(body), {
		status: 200,
		headers: { "content-type": "application/json" },
		...init
	});

const makeCtx = (fetchMock: typeof globalThis.fetch): BobbinContext =>
	createBobbinClient({ serviceUrl: "https://bobbin.test", fetch: fetchMock });

describe("knot.archive (binary passthrough)", () => {
	it("throws ClientResponseError on a non-2xx archive response", async () => {
		const fetchMock = vi
			.fn<typeof globalThis.fetch>()
			.mockResolvedValue(jsonResponse({ error: "UpstreamGone" }, { status: 502 }));
		const err = await knot
			.archive(makeCtx(fetchMock), { repo: "did:plc:x/r", ref: "main" })
			.catch((e: unknown) => e);
		expect(err).toBeInstanceOf(ClientResponseError);
		expect((err as ClientResponseError).status).toBe(502);
	});
});
