/**
 * doctor-history-versioning.test.mjs - doctor history JSONL schema contract.
 *
 * Purpose: prove doctor history remains a versioned append-only diagnostic
 * contract while preserving reads of pre-version history rows.
 */
import assert from "node:assert/strict";
import {
	mkdirSync,
	mkdtempSync,
	readFileSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, test } from "vitest";
import { readDoctorHistory, runSFDoctor } from "../doctor.js";

const tmpDirs = [];

afterEach(() => {
	while (tmpDirs.length > 0) {
		const dir = tmpDirs.pop();
		if (dir) rmSync(dir, { recursive: true, force: true });
	}
});

function makeProject() {
	const dir = mkdtempSync(join(tmpdir(), "sf-doctor-history-versioning-"));
	tmpDirs.push(dir);
	mkdirSync(join(dir, ".sf"), { recursive: true });
	return dir;
}

describe("doctor history versioning", () => {
	test("runSFDoctor_records_schema_versioned_history_rows", async () => {
		const project = makeProject();

		await runSFDoctor(project, { scope: "project" });

		const lines = readFileSync(
			join(project, ".sf", "doctor-history.jsonl"),
			"utf-8",
		)
			.trim()
			.split("\n");
		const row = JSON.parse(lines.at(-1));

		assert.equal(row.schemaVersion, 1);
		assert.equal(typeof row.ts, "string");
		assert.equal(typeof row.ok, "boolean");
	});

	test("readDoctorHistory_treats_legacy_missing_schemaVersion_as_version_1", async () => {
		const project = makeProject();
		writeFileSync(
			join(project, ".sf", "doctor-history.jsonl"),
			JSON.stringify({
				ts: "2026-05-07T00:00:00.000Z",
				ok: true,
				errors: 0,
				warnings: 0,
				fixes: 0,
				codes: [],
				summary: "Clean",
			}) + "\n",
			"utf-8",
		);

		const [row] = await readDoctorHistory(project);

		assert.equal(row.schemaVersion, 1);
		assert.equal(row.summary, "Clean");
	});
});
