/* @vitest-environment node */

import { describe, it, expect } from "vitest";
import {
	readRouteBranchFromPathname,
	isSearchRoutePathname,
	replaceBranchInPathnameOrFallback,
	buildNextSearchQueryString,
	buildNextUrlForBranchSwitch,
} from "./branchSwitch.js";

describe("lib/frontend/quickNav/branchSwitch", () => {
	it("readRouteBranchFromPathname returns the first segment when valid", () => {
		expect(readRouteBranchFromPathname("/NL01")).toBe("NL01");
		expect(readRouteBranchFromPathname("/NL01/2025/12/31")).toBe("NL01");
		expect(readRouteBranchFromPathname("/search")).toBe(null);
		expect(readRouteBranchFromPathname("/nl01")).toBe(null);
	});

	it("isSearchRoutePathname detects /:branch/search", () => {
		expect(isSearchRoutePathname("/NL01/search")).toBe(true);
		expect(isSearchRoutePathname("/NL01/search/extra")).toBe(true);
		expect(isSearchRoutePathname("/NL01")).toBe(false);
		expect(isSearchRoutePathname("/search")).toBe(false);
	});

	it("replaceBranchInPathnameOrFallback replaces only the first segment", () => {
		expect(replaceBranchInPathnameOrFallback("/NL01/2025/12/31", "NL20")).toBe(
			"/NL20/2025/12/31"
		);

		// No valid branch -> fallback to branch root
		expect(replaceBranchInPathnameOrFallback("/search", "NL20")).toBe("/NL20");
	});

	it("buildNextSearchQueryString drops legacy SINGLE branch= and keeps other params", () => {
		const qs = buildNextSearchQueryString({
			currentSearch: "?q=x&branch=NL01&limit=200",
			currentRouteBranch: "NL01",
			nextBranch: "NL20",
		});

		expect(qs).toBe("?q=x&limit=200");
	});

	it("buildNextSearchQueryString keeps MULTI branches (sorted deterministically)", () => {
		const qs = buildNextSearchQueryString({
			currentSearch: "?q=x&scope=multi&branches=NL20,NL06",
			currentRouteBranch: "NL01",
			nextBranch: "NL02",
		});

		expect(qs).toBe("?q=x&scope=multi&branches=NL06%2CNL20");
	});

	it("buildNextUrlForBranchSwitch preserves deep path and normalizes Search URLs", () => {
		expect(
			buildNextUrlForBranchSwitch({
				pathname: "/NL01/2025/12/31",
				search: "",
				nextBranch: "NL20",
			})
		).toBe("/NL20/2025/12/31");

		expect(
			buildNextUrlForBranchSwitch({
				pathname: "/NL01/search",
				search: "?q=x&branch=NL01&limit=200",
				nextBranch: "NL20",
			})
		).toBe("/NL20/search?q=x&limit=200");
	});
});
