/**
 * sf-db-task-frontmatter.test.mjs - DB task metadata integration contracts.
 *
 * Purpose: prove the SQLite task and task_specs tables persist normalized
 * task metadata and expose it through getTask without a sidecar state store.
 */

import assert from "node:assert/strict";
import { test } from "vitest";
import {
	closeDatabase,
	getTask,
	getTaskSpec,
	insertMilestone,
	insertSlice,
	insertTask,
	openDatabase,
	updateTaskStatus,
	upsertTaskPlanning,
} from "../sf-db.js";

test("sfDb_task_frontmatter_round_trips_through_task_and_spec_rows", () => {
	closeDatabase();
	assert.equal(openDatabase(":memory:"), true);
	try {
		insertMilestone({ id: "M001", title: "Milestone", status: "active" });
		insertSlice({
			milestoneId: "M001",
			id: "S01",
			title: "Slice",
			status: "pending",
		});
		insertTask({
			milestoneId: "M001",
			sliceId: "S01",
			id: "T01",
			title: "Task",
			status: "pending",
		});
		upsertTaskPlanning("M001", "S01", "T01", {
			title: "Task",
			description: "Purpose: prove metadata persistence.",
			estimate: "45m",
			files: ["src/planned.ts"],
			verify: "npm test",
			inputs: ["src/input.ts"],
			expectedOutput: ["src/output.ts"],
			risk: "high",
			mutationScope: "systemic",
			verification: "integration",
			planApproval: "pending",
			schedulerStatus: "dispatched",
			estimatedEffort: 45,
			dependencies: ["T00"],
			blocksParallel: true,
			requiresUserInput: true,
			autoRetry: false,
			maxRetries: 0,
		});

		const task = getTask("M001", "S01", "T01");
		assert.equal(task.frontmatter.risk, "high");
		assert.equal(task.frontmatter.mutationScope, "systemic");
		assert.equal(task.frontmatter.verification, "integration");
		assert.equal(task.frontmatter.planApproval, "pending");
		assert.equal(task.frontmatter.schedulerStatus, "dispatched");
		assert.equal(task.frontmatter.estimatedEffort, 45);
		assert.deepEqual(task.frontmatter.dependencies, ["T00"]);
		assert.equal(task.frontmatter.blocksParallel, true);
		assert.equal(task.frontmatter.autoRetry, false);
		assert.deepEqual(task.frontmatter.keyFiles, ["src/planned.ts"]);

		const spec = getTaskSpec("M001", "S01", "T01");
		assert.equal(spec.risk, "high");
		assert.equal(spec.mutation_scope, "systemic");
		assert.equal(spec.verification_type, "integration");
		assert.equal(spec.plan_approval, "pending");
		assert.equal(spec.estimated_effort, 45);
		assert.equal(spec.dependencies, JSON.stringify(["T00"]));
		assert.equal(spec.blocks_parallel, 1);
		assert.equal(spec.requires_user_input, 1);
		assert.equal(spec.auto_retry, 0);
		assert.equal(spec.max_retries, 0);
		assert.equal("scheduler_status" in spec, false);

		updateTaskStatus("M001", "S01", "T01", "done", "2026-05-08T00:00:00.000Z");
		const completed = getTask("M001", "S01", "T01");
		assert.equal(completed.frontmatter.taskStatus, "done");
		assert.equal(completed.frontmatter.schedulerStatus, "dispatched");
	} finally {
		closeDatabase();
	}
});
