import { DIAGNOSTIC_CODES } from "@/lib/types";
import { DIAGNOSTIC_COMPONENTS, EVENT_COPY, componentLabel, copyFor } from "./eventCopy";

test("the enum holds the fifteen codes the store defines", () => {
	expect(DIAGNOSTIC_CODES).toHaveLength(15);
	expect(new Set(DIAGNOSTIC_CODES).size).toBe(15);
});

test("every code has copy, and no copy belongs to a code that does not exist", () => {
	for (const code of DIAGNOSTIC_CODES) {
		const copy = EVENT_COPY[code];
		expect(copy, code).toBeDefined();
		expect(copy.title.length, code).toBeGreaterThan(0);
		expect(copy.impact.length, code).toBeGreaterThan(0);
		expect(copy.remediation.length, code).toBeGreaterThan(0);
	}
	expect(Object.keys(EVENT_COPY).sort()).toEqual([...DIAGNOSTIC_CODES].sort());
});

test("titles are distinct, so two open episodes never read as the same event", () => {
	const titles = DIAGNOSTIC_CODES.map((code) => EVENT_COPY[code].title);
	expect(new Set(titles).size).toBe(titles.length);
});

test("a code this build has never heard of falls back to the code itself", () => {
	// The server is the authority on the enum; a newer one can send a sixteenth.
	const copy = copyFor("nonsense.code" as (typeof DIAGNOSTIC_CODES)[number]);
	expect(copy.title).toBe("nonsense.code");
	expect(copy.remediation.length).toBeGreaterThan(0);
});

test("the component options are the code prefixes, deduplicated and in enum order", () => {
	expect(DIAGNOSTIC_COMPONENTS).toEqual([
		"disk",
		"blocklist",
		"certificate",
		"query_log",
		"upstream_history",
		"upstream",
		"client_names",
		"clients",
		"listener",
		"configuration",
	]);
});

test("component labels read as prose without inventing a name", () => {
	expect(componentLabel("query_log")).toBe("Query log");
	expect(componentLabel("disk")).toBe("Disk");
});

test("the legacy upstream_history code keeps its copy, so a retained episode still reads as prose", () => {
	// Nothing emits it any more, but stored rows outlive the subsystem and the
	// list endpoint passes their codes through verbatim.
	expect(DIAGNOSTIC_CODES).toContain("upstream_history.write");
	const copy = EVENT_COPY["upstream_history.write"];
	expect(copy.title).toBe("Upstream history write failed");
	expect(copy.impact).toMatch(/no longer runs/);
});

test("the recreated-log copy covers a planned schema change as well as an unreadable file", () => {
	const copy = EVENT_COPY["query_log.recreated"];
	// The planned cause leads, because it is the one an upgrade produces; the
	// unreadable file is the other cause and must not be dropped from the copy.
	expect(copy.impact).toMatch(/schema/);
	expect(copy.impact).toMatch(/could not be read/);
});
