/**
 * MCP tools for rData (analytics dashboard config).
 *
 * Tools: rdata_list_tracked_apps
 */

import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import type { SyncServer } from "../local-first/sync-server";
import { dataDocId } from "../../modules/rdata/schemas";
import type { DataDoc } from "../../modules/rdata/schemas";
import { resolveAccess, accessDeniedResponse } from "./_auth";

export function registerDataTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rdata_list_tracked_apps",
		"List tracked analytics apps and dashboard config",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
		},
		async ({ space, token }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

			return {
				content: [{
					type: "text",
					text: JSON.stringify({
						trackedApps: Object.values(doc.trackedApps || {}),
						dashboardConfig: doc.dashboardConfig,
					}, null, 2),
				}],
			};
		},
	);
}
