/**
 * queue-order-db.test.mjs — DB-backed milestone priority/order.
 *
 * Purpose: prove queue reordering is persisted in SQLite when available, with
 * legacy JSON kept only as fallback for DB-unavailable contexts.
 */
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 { loadQueueOrder, saveQueueOrder } from "../queue-order.js";
import {
	closeDatabase,
	getAllMilestones,
	insertMilestone,
	openDatabase,
} from "../sf-db.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-queue-order-db-"));
	tmpDirs.push(dir);
	mkdirSync(join(dir, ".sf"), { recursive: true });
	openDatabase(join(dir, ".sf", "sf.db"));
	insertMilestone({ id: "M001", title: "One", status: "queued" });
	insertMilestone({ id: "M002", title: "Two", status: "queued" });
	insertMilestone({ id: "M003", title: "Three", status: "queued" });
	return dir;
}

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

	saveQueueOrder(project, ["M003", "M001", "M002"]);

	assert.deepEqual(loadQueueOrder(project), ["M003", "M001", "M002"]);
	assert.equal(existsSync(join(project, ".sf", "QUEUE-ORDER.json")), false);
	assert.deepEqual(
		getAllMilestones().map((m) => [m.id, m.sequence]),
		[
			["M003", 1],
			["M001", 2],
			["M002", 3],
		],
	);
});
