/**
 * Path-traversal ID validation for handleCompleteSlice
 * (validation-safe-id-path-segments self-feedback fix)
 *
 * Asserts that handleCompleteSlice rejects unsafe milestoneId / sliceId
 * values before they reach any filesystem path interpolation or DB write.
 */

import assert from "node:assert/strict";
import { test } from 'vitest';
import { handleCompleteSlice } from "../tools/complete-slice.ts";
import type { CompleteSliceParams } from "../types.ts";

/** Minimal valid-looking params — fields beyond milestoneId/sliceId are
 *  irrelevant because the safe-id check fires before they are used. */
function baseParams(): CompleteSliceParams {
	return {
		sliceId: "S01",
		milestoneId: "M001",
		sliceTitle: "Test Slice",
		oneLiner: "one-liner",
		narrative: "narrative",
		verification: "all tests pass",
		deviations: "None.",
		knownLimitations: "None.",
		followUps: "None.",
		keyFiles: [],
		keyDecisions: [],
		patternsEstablished: [],
		observabilitySurfaces: [],
		provides: [],
		requirementsSurfaced: [],
		drillDownPaths: [],
		affects: [],
		requirementsAdvanced: [],
		requirementsValidated: [],
		requirementsInvalidated: [],
		filesModified: [],
		requires: [],
		uatContent: "## UAT\n\nSmoke test passes.",
	};
}

test("handleCompleteSlice rejects path-traversal milestoneId", async () => {
	const params = { ...baseParams(), milestoneId: "../etc" };
	const result = await handleCompleteSlice(params, "/tmp/sf-safe-id-test");

	assert.ok(
		"error" in result,
		"result must be an error response",
	);
	const err = result as { error: string; field?: string; reason?: string };
	assert.equal(err.error, "unsafe_id", 'error must be "unsafe_id"');
	assert.ok(
		typeof err.field === "string" && err.field.length > 0,
		"field must be a non-empty string",
	);
	assert.ok(
		typeof err.reason === "string" && err.reason.length > 0,
		"reason must be a non-empty string",
	);
});

test("handleCompleteSlice rejects path-traversal sliceId", async () => {
	const params = { ...baseParams(), sliceId: "S01/../../x" };
	const result = await handleCompleteSlice(params, "/tmp/sf-safe-id-test");

	assert.ok(
		"error" in result,
		"result must be an error response",
	);
	const err = result as { error: string; field?: string; reason?: string };
	assert.equal(err.error, "unsafe_id", 'error must be "unsafe_id"');
	assert.ok(
		typeof err.field === "string" && err.field.length > 0,
		"field must be a non-empty string",
	);
	assert.ok(
		typeof err.reason === "string" && err.reason.length > 0,
		"reason must be a non-empty string",
	);
});
