/**
 * MCP tools for rForum (Discourse instance provisioning).
 * Global-scoped (not per-space).
 *
 * Tools: rforum_list_instances, rforum_get_instance
 */

import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import type { SyncServer } from "../local-first/sync-server";
import { FORUM_DOC_ID } from "../../modules/rforum/schemas";
import type { ForumDoc } from "../../modules/rforum/schemas";
import { verifyToken } from "../auth";

export function registerForumTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rforum_list_instances",
		"List Discourse forum instances (requires auth — global scope)",
		{
			token: z.string().describe("JWT auth token (required — admin data)"),
			status: z.string().optional().describe("Filter by status (pending, active, error, etc.)"),
		},
		async ({ token, status }) => {
			try {
				await verifyToken(token);
			} catch {
				return { content: [{ type: "text", text: JSON.stringify({ error: "Invalid or expired token" }) }], isError: true };
			}

			const doc = syncServer.getDoc<ForumDoc>(FORUM_DOC_ID);
			if (!doc) return { content: [{ type: "text", text: JSON.stringify({ error: "No forum data found" }) }] };

			let instances = Object.values(doc.instances || {});
			if (status) instances = instances.filter(i => i.status === status);

			const summary = instances.map(i => ({
				id: i.id, name: i.name, domain: i.domain,
				status: i.status, provider: i.provider,
				region: i.region, vpsIp: i.vpsIp,
				sslProvisioned: i.sslProvisioned,
				createdAt: i.createdAt, provisionedAt: i.provisionedAt,
			}));

			return { content: [{ type: "text", text: JSON.stringify(summary, null, 2) }] };
		},
	);

	server.tool(
		"rforum_get_instance",
		"Get full details of a forum instance including provision logs",
		{
			token: z.string().describe("JWT auth token"),
			instance_id: z.string().describe("Instance ID"),
		},
		async ({ token, instance_id }) => {
			try {
				await verifyToken(token);
			} catch {
				return { content: [{ type: "text", text: JSON.stringify({ error: "Invalid or expired token" }) }], isError: true };
			}

			const doc = syncServer.getDoc<ForumDoc>(FORUM_DOC_ID);
			const instance = doc?.instances?.[instance_id];
			if (!instance) return { content: [{ type: "text", text: JSON.stringify({ error: "Instance not found" }) }] };

			const logs = doc!.provisionLogs?.[instance_id] || [];
			return { content: [{ type: "text", text: JSON.stringify({ instance, provisionLogs: logs }, null, 2) }] };
		},
	);
}
