/**
 * MCP tools for rMaps (map annotations, saved routes, meeting points).
 *
 * Tools: rmaps_list_annotations, rmaps_list_routes, rmaps_list_meeting_points
 */

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

export function registerMapsTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rmaps_list_annotations",
		"List map annotations (pins, notes, areas) in a space",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			type: z.string().optional().describe("Filter by type: pin, note, or area"),
		},
		async ({ space, token, type }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

			const doc = syncServer.getDoc<MapsDoc>(mapsDocId(space));
			if (!doc) return { content: [{ type: "text" as const, text: JSON.stringify({ annotations: [] }) }] };

			let annotations = Object.values(doc.annotations || {});
			if (type) annotations = annotations.filter(a => a.type === type);

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

	server.tool(
		"rmaps_list_routes",
		"List saved routes in a space",
		{
			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<MapsDoc>(mapsDocId(space));
			if (!doc) return { content: [{ type: "text" as const, text: JSON.stringify({ routes: [] }) }] };

			const routes = Object.values(doc.savedRoutes || {}).map(r => ({
				id: r.id, name: r.name,
				waypointCount: r.waypoints?.length ?? 0,
				authorDid: r.authorDid, createdAt: r.createdAt,
			}));

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

	server.tool(
		"rmaps_list_meeting_points",
		"List saved meeting points in a space",
		{
			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<MapsDoc>(mapsDocId(space));
			if (!doc) return { content: [{ type: "text" as const, text: JSON.stringify({ meetingPoints: [] }) }] };

			const points = Object.values(doc.savedMeetingPoints || {});
			return { content: [{ type: "text" as const, text: JSON.stringify(points, null, 2) }] };
		},
	);
}
