import { diagnosticsBounds, relatedBounds, RELATED_WINDOW_SECONDS } from "./relatedLinks";
import { queriesFilterOf, validateActivitySearch } from "./search";

const TS = 1_700_000_000;

test("an unbounded origin falls back to the window either side of the query", () => {
	expect(relatedBounds(TS, { since: undefined, until: undefined })).toEqual({
		since: TS - RELATED_WINDOW_SECONDS,
		until: TS + RELATED_WINDOW_SECONDS,
	});
});

test("a bounded origin carries both of its bounds through unchanged", () => {
	expect(relatedBounds(TS, { since: 1, until: 2 })).toEqual({ since: 1, until: 2 });
});

test("a half-bounded origin keeps its half and falls back on the other", () => {
	expect(relatedBounds(TS, { since: 1, until: undefined })).toEqual({
		since: 1,
		until: TS + RELATED_WINDOW_SECONDS,
	});
	expect(relatedBounds(TS, { since: undefined, until: 2 })).toEqual({
		since: TS - RELATED_WINDOW_SECONDS,
		until: 2,
	});
});

test("an origin bound of zero is a bound, not a missing one", () => {
	expect(relatedBounds(TS, { since: 0, until: 0 })).toEqual({ since: 0, until: 0 });
});

test("the diagnostics window is the fixed window either side of the query, never inherited", () => {
	expect(diagnosticsBounds(TS)).toEqual({ since: TS - RELATED_WINDOW_SECONDS, until: TS + RELATED_WINDOW_SECONDS });
	expect(diagnosticsBounds(0)).toEqual({ since: -RELATED_WINDOW_SECONDS, until: RELATED_WINDOW_SECONDS });
});

/**
 * The admin half of the server's `since <= ts < until` window contract
 * (queries_repo.zig): what a related link emits has to survive the validation
 * the Activity route puts every search through, or the link would silently open
 * a wider window than it named. Inclusion at the edges is the server's property
 * and is tested there; this pins that the bounds arrive intact.
 */
test("bounds emitted by a related link round-trip through the Activity search to the same filter", () => {
	const origin = { since: undefined, until: TS + 3_600 };
	const emitted = { mode: "history", domain: "ads.example.com", ...relatedBounds(TS, origin) };

	const applied = validateActivitySearch(emitted);

	expect(applied.mode).toBe("history");
	expect(applied.since).toBe(emitted.since);
	expect(applied.until).toBe(emitted.until);
	expect(queriesFilterOf(applied)).toEqual({
		domain: "ads.example.com",
		since: TS - RELATED_WINDOW_SECONDS,
		until: TS + 3_600,
	});
});
