import { describe, expect, it, vi } from "vitest";
import * as knotmirror from "./knotmirror";

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

describe("knotmirror.tree", () => {
	it("adapts the temporary tree response and fetches the readme blob", async () => {
		const fetchMock = vi.fn<typeof globalThis.fetch>().mockImplementation(async (input) => {
			const url = new URL(String(input));
			if (url.pathname.endsWith("getTree")) {
				return jsonResponse({
					ref: "main",
					files: [
						{
							name: "README.md",
							mode: "100644",
							size: 12,
							last_commit: {
								hash: "abc",
								message: "docs",
								when: "2026-07-01T00:00:00Z"
							}
						}
					]
				});
			}
			return new Response("# hello", {
				status: 200,
				headers: { "content-type": "text/plain" }
			});
		});

		const ctx = knotmirror.createKnotMirrorClient("https://mirror.test", fetchMock);
		const tree = await knotmirror.tree(ctx, {
			repo: "did:plc:repo",
			ref: "main",
			path: "docs"
		});

		expect(tree.readme).toEqual({ filename: "README.md", contents: "# hello" });
		expect(tree.files[0]).toMatchObject({ name: "README.md", mode: "100644" });
		expect(fetchMock).toHaveBeenCalledTimes(2);
		const blobUrl = new URL(String(fetchMock.mock.calls[1][0]));
		expect(blobUrl.pathname).toBe("/xrpc/sh.tangled.git.temp.getBlob");
		expect(blobUrl.searchParams.get("path")).toBe("docs/README.md");
	});
});

describe("knotmirror.languages", () => {
	it("uses the temporary languages endpoint", async () => {
		const fetchMock = vi
			.fn<typeof globalThis.fetch>()
			.mockResolvedValue(
				jsonResponse({ ref: "main", languages: [{ name: "TypeScript", size: 10 }] })
			);
		const ctx = knotmirror.createKnotMirrorClient("https://mirror.test", fetchMock);

		await knotmirror.languages(ctx, { repo: "did:plc:repo", ref: "main" });

		const url = new URL(String(fetchMock.mock.calls[0][0]));
		expect(url.pathname).toBe("/xrpc/sh.tangled.git.temp.listLanguages");
	});
});
