/**
 * plan-task-evidence.test.mjs — task planning evidence.
 *
 * Purpose: prove task planning records structured DB evidence while rendering
 * generated task plan projections from the database.
 */
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,
	getTaskAuditTrail,
	insertMilestone,
	insertSlice,
	openDatabase,
} from "../sf-db.js";
import { handlePlanTask } from "../tools/plan-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-plan-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("handlePlanTask_when_successful_records_plan_task_evidence", async () => {
	const project = makeProject();

	const result = await handlePlanTask(
		{
			milestoneId: "M001",
			sliceId: "S01",
			taskId: "T01",
			title: "Task plan evidence",
			description: "Persist task planning evidence.",
			estimate: "small",
			files: ["src/resources/extensions/sf/tools/plan-task.js"],
			verify: "npm test -- plan-task",
			inputs: ["DB-backed task"],
			expectedOutput: ["Evidence row"],
			observabilityImpact: "Task evidence is queryable.",
		},
		project,
	);

	assert.equal(result.error, undefined);
	const trail = getTaskAuditTrail("M001", "S01", "T01");
	assert.equal(trail.length, 1);
	assert.equal(trail[0].evidence_type, "plan_task");
	assert.match(trail[0].content, /Task plan evidence/);
	assert.match(trail[0].content, /Task evidence is queryable/);
});
