/**
 * MCP tools for rMeets (video meeting scheduling).
 *
 * Tools: rmeets_list_meetings, rmeets_get_history
 */

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

export function registerMeetsTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rmeets_list_meetings",
		"List scheduled meetings in a space",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			upcoming_only: z.boolean().optional().describe("Only future meetings (default true)"),
		},
		async ({ space, token, upcoming_only }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

			let meetings = Object.values(doc.meetings || {});
			if (upcoming_only !== false) {
				meetings = meetings.filter(m => m.scheduledAt >= Date.now());
			}
			meetings.sort((a, b) => a.scheduledAt - b.scheduledAt);

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

	server.tool(
		"rmeets_get_history",
		"Get meeting history with participant counts",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			limit: z.number().optional().describe("Max results (default 20)"),
		},
		async ({ space, token, limit }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

			const history = (doc.meetingHistory || [])
				.slice(-(limit || 20))
				.reverse();

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