/**
 * complete-task-evidence.test.mjs — task completion evidence.
 *
 * Purpose: prove task completion records structured DB evidence in addition
 * to generated SUMMARY markdown and verification rows.
 */
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,
	getTask,
	getTaskAuditTrail,
	insertMilestone,
	insertSlice,
	openDatabase,
} from "../sf-db.js";
import { handleCompleteTask } from "../tools/complete-task.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-task-evidence-"));
	tmpDirs.push(dir);
	mkdirSync(join(dir, ".sf", "milestones", "M001", "slices", "S01", "tasks"), {
		recursive: true,
	});
	openDatabase(join(dir, ".sf", "sf.db"));
	insertMilestone({ id: "M001", title: "Evidence", status: "active" });
	insertSlice({
		milestoneId: "M001",
		id: "S01",
		title: "Slice",
		status: "pending",
	});
	return dir;
}

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

	const result = await handleCompleteTask(
		{
			milestoneId: "M001",
			sliceId: "S01",
			taskId: "T01",
			oneLiner: "Task finished with evidence",
			narrative: "The behavior is implemented.",
			verification: "Focused test passed.",
			// ADR-0000 (SF v70): purpose_trace is required at completion time.
			purposeTrace:
				"Served the slice-goal clause about recording structured evidence per task.",
			verificationEvidence: [
				{
					command: "npm test -- complete-task",
					exitCode: 0,
					verdict: "passed",
					durationMs: 42,
				},
			],
			keyDecisions: ["Keep task evidence in DB"],
			keyFiles: ["src/resources/extensions/sf/tools/complete-task.js"],
		},
		project,
	);

	assert.equal(result.error, undefined);
	assert.equal(getTask("M001", "S01", "T01").status, "complete");
	const trail = getTaskAuditTrail("M001", "S01", "T01");
	assert.equal(trail.length, 1);
	assert.equal(trail[0].evidence_type, "completion_summary");
	assert.match(trail[0].content, /Task finished with evidence/);
	assert.match(trail[0].content, /Keep task evidence in DB/);
});
