import assert from "node:assert/strict";
import { test } from "vitest";
import {
	normalizeToolCommandRegistry,
	validateToolCommandRegistry,
} from "../uok/tool-command-registry.js";

test("normalizeToolCommandRegistry_when_commands_and_daemon_services_present_returns_worker_tool_allowlist", () => {
	assert.deepEqual(
		normalizeToolCommandRegistry({
			commands: {
				test: " npm run test:unit ",
				typecheck: "npm run typecheck:extensions",
			},
			daemonServices: [" postgres ", "redis", "redis"],
		}),
		{
			schemaVersion: 1,
			commands: {
				test: "npm run test:unit",
				typecheck: "npm run typecheck:extensions",
			},
			daemonServices: ["postgres", "redis"],
			allowedCommands: ["npm run test:unit", "npm run typecheck:extensions"],
			allowedCommandNames: ["test", "typecheck"],
			allowedDaemonServices: ["postgres", "redis"],
		},
	);
});

test("normalizeToolCommandRegistry_when_fields_missing_returns_empty_allowlists", () => {
	assert.deepEqual(normalizeToolCommandRegistry({}), {
		schemaVersion: 1,
		commands: {},
		daemonServices: [],
		allowedCommands: [],
		allowedCommandNames: [],
		allowedDaemonServices: [],
	});
});

test("validateToolCommandRegistry_when_commands_not_object_reports_clear_issue", () => {
	const result = validateToolCommandRegistry({
		commands: ["npm test"],
		daemonServices: [],
	});

	assert.equal(result.ok, false);
	assert.deepEqual(result.issues, ["commands must be an object"]);
});

test("validateToolCommandRegistry_when_command_or_daemon_service_empty_reports_paths", () => {
	const result = validateToolCommandRegistry({
		commands: {
			test: "",
		},
		daemonServices: ["postgres", ""],
	});

	assert.equal(result.ok, false);
	assert.deepEqual(result.issues, [
		"commands.test must be a non-empty string",
		"daemonServices[1] must be a non-empty string",
	]);
});

test("normalizeToolCommandRegistry_when_droid_services_field_present_treats_it_as_legacy_daemon_services", () => {
	assert.deepEqual(
		normalizeToolCommandRegistry({
			commands: {
				build: "npm run build:core",
			},
			services: ["postgres"],
		}),
		{
			schemaVersion: 1,
			commands: {
				build: "npm run build:core",
			},
			daemonServices: ["postgres"],
			allowedCommands: ["npm run build:core"],
			allowedCommandNames: ["build"],
			allowedDaemonServices: ["postgres"],
		},
	);
});
