/* @vitest-environment node */

import { describe, it, expect } from "vitest";
import { buildQsirchQuery, sanitizeUserQuery } from "./queryBuilder.js";

describe("lib/search/queryBuilder", () => {
	it("sanitizes user query (removes ':' and quotes)", () => {
		expect(sanitizeUserQuery('path:"/Public"')).toBe("path /Public");
	});

	it("builds branch-scoped query with date range", () => {
		const q = buildQsirchQuery({
			mode: "branch",
			branches: ["NL20"],
			q: "bridgestone",
			from: "2025-12-01",
			to: "2025-12-31",
			dateField: "modified",
			pathPrefix: "/Niederlassungen",
		});

		expect(q).toContain('path:"/Niederlassungen/NL20"');
		expect(q).toContain('extension:"pdf"');
		expect(q).toContain('modified:"2025-12-01..2025-12-31"');
		expect(q).toContain("bridgestone");
	});

	it("builds multi-branch query by replicating filters per branch", () => {
		const q = buildQsirchQuery({
			mode: "multi",
			branches: ["NL01", "NL02"],
			q: "invoice",
			from: "2025-01-01",
			to: "2025-01-31",
			dateField: "modified",
			pathPrefix: "/Niederlassungen",
		});

		// Both branch clauses must include the same constraints.
		expect(q).toContain('path:"/Niederlassungen/NL01"');
		expect(q).toContain('path:"/Niederlassungen/NL02"');
		expect(q).toContain(" OR ");
		expect(q).toContain('extension:"pdf"');
	});

	it("builds global query for all", () => {
		const q = buildQsirchQuery({
			mode: "all",
			branches: null,
			q: null,
			from: null,
			to: "2025-12-31",
			dateField: "modified",
			pathPrefix: "/Niederlassungen",
		});

		expect(q).toContain('path:"/Niederlassungen"');
		expect(q).toContain("modified:<=2025-12-31");
	});
});
