/**
 * complete-milestone-evidence.test.mjs — milestone completion evidence.
 *
 * Purpose: prove milestone completion records structured DB evidence, not only
 * a generated summary markdown file.
 */
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";
import {
	closeDatabase,
	getMilestone,
	getMilestoneAuditTrail,
	insertMilestone,
	insertSlice,
	insertTask,
	openDatabase,
} from "../sf-db.js";
import { handleCompleteMilestone } from "../tools/complete-milestone.js";

const tmpDirs = [];

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

function makeProject() {
	const dir = mkdtempSync(join(tmpdir(), "sf-complete-milestone-evidence-"));
	tmpDirs.push(dir);
	mkdirSync(join(dir, ".sf", "milestones", "M001"), { recursive: true });
	openDatabase(join(dir, ".sf", "sf.db"));
	insertMilestone({ id: "M001", title: "Evidence", status: "active" });
	insertSlice({
		milestoneId: "M001",
		id: "S01",
		title: "Slice",
		status: "complete",
	});
	insertTask({
		milestoneId: "M001",
		sliceId: "S01",
		id: "T01",
		title: "Task",
		status: "complete",
	});
	return dir;
}

test("handleCompleteMilestone_when_successful_records_completion_summary_evidence", async () => {
	const project = makeProject();

	const result = await handleCompleteMilestone(
		{
			milestoneId: "M001",
			title: "Evidence",
			verificationPassed: true,
			oneLiner: "Finished with evidence",
			narrative: "All slices and tasks are closed.",
			successCriteriaResults: "Passed.",
			definitionOfDoneResults: "Satisfied.",
			keyDecisions: ["Keep DB authoritative"],
			keyFiles: ["src/resources/extensions/sf/sf-db.js"],
			lessonsLearned: ["Evidence belongs in SQLite"],
		},
		project,
	);

	assert.equal(result.error, undefined);
	assert.equal(getMilestone("M001").status, "complete");
	const trail = getMilestoneAuditTrail("M001");
	assert.equal(trail.length, 1);
	assert.equal(trail[0].evidence_type, "completion_summary");
	assert.match(trail[0].content, /Finished with evidence/);
	assert.match(trail[0].content, /Keep DB authoritative/);
});
