/* @vitest-environment node */

import { describe, it, expect } from "vitest";
import { buildPdfUrl, buildPdfDownloadUrl } from "./pdfUrl.js";

describe("lib/frontend/explorer/pdfUrl", () => {
	it("builds the expected PDF stream URL", () => {
		const url = buildPdfUrl({
			branch: "NL01",
			year: "2024",
			month: "10",
			day: "23",
			filename: "test.pdf",
		});

		expect(url).toBe("/api/files/NL01/2024/10/23/test.pdf");
	});

	it("encodes filenames with spaces and special characters (#, &, +, %)", () => {
		const filename = "Lieferschein #1 & Co +100%.pdf";

		const url = buildPdfUrl({
			branch: "NL01",
			year: "2024",
			month: "10",
			day: "23",
			filename,
		});

		expect(url).toBe(
			"/api/files/NL01/2024/10/23/Lieferschein%20%231%20%26%20Co%20%2B100%25.pdf"
		);
	});

	it("encodes unicode filenames safely", () => {
		const filename = "Müller Übergabe.pdf";

		const url = buildPdfUrl({
			branch: "NL01",
			year: "2024",
			month: "10",
			day: "23",
			filename,
		});

		// We intentionally compare against encodeURIComponent behavior
		// to avoid hand-maintaining unicode encodings.
		const expected = `/api/files/NL01/2024/10/23/${encodeURIComponent(
			filename
		)}`;

		expect(url).toBe(expected);
	});

	it("builds the download URL with ?download=1", () => {
		const url = buildPdfDownloadUrl({
			branch: "NL01",
			year: "2024",
			month: "10",
			day: "23",
			filename: "test.pdf",
		});

		expect(url).toBe("/api/files/NL01/2024/10/23/test.pdf?download=1");
	});

	it("throws for missing or empty segments", () => {
		expect(() =>
			buildPdfUrl({
				branch: "NL01",
				year: "2024",
				month: "10",
				day: "23",
				filename: "",
			})
		).toThrow(/must not be empty/i);

		expect(() =>
			buildPdfUrl({
				branch: "",
				year: "2024",
				month: "10",
				day: "23",
				filename: "test.pdf",
			})
		).toThrow(/branch/i);
	});
});
