/**
 * triage-resolution-db.test.mjs — DB-backed replan trigger coverage.
 *
 * Purpose: prove triage replan execution stamps structured slice state while
 * retaining the markdown marker as compatibility evidence.
 */
import assert from "node:assert/strict";
import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";
import {
	closeDatabase,
	getSlice,
	insertMilestone,
	insertSlice,
	openDatabase,
} from "../sf-db.js";
import { executeReplan } from "../triage-resolution.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-triage-resolution-"));
	mkdirSync(join(dir, ".sf"), { recursive: true });
	tmpDirs.push(dir);
	return dir;
}

test("executeReplan_stamps_db_replan_trigger_and_writes_marker", () => {
	const project = makeProject();
	assert.equal(openDatabase(join(project, ".sf", "sf.db")), true);
	insertMilestone({ id: "M001", title: "Milestone", status: "active" });
	insertSlice({ milestoneId: "M001", id: "S01", title: "Slice" });

	const ok = executeReplan(project, "M001", "S01", {
		id: "cap-1",
		text: "Need to replan the slice",
		rationale: "new dependency",
	});

	assert.equal(ok, true);
	const slice = getSlice("M001", "S01");
	assert.equal(typeof slice.replan_triggered_at, "string");
	assert.ok(slice.replan_triggered_at.length > 0);
	assert.equal(
		existsSync(
			join(
				project,
				".sf",
				"milestones",
				"M001",
				"slices",
				"S01",
				"S01-REPLAN-TRIGGER.md",
			),
		),
		true,
	);
});
