/**
 * MCP tools for rTube (video playlists & watch parties).
 *
 * Tools: rtube_list_playlists, rtube_get_watch_party
 */

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

export function registerTubeTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rtube_list_playlists",
		"List video playlists 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<TubeDoc>(tubeDocId(space));
			if (!doc) return { content: [{ type: "text", text: JSON.stringify({ error: "No tube data found" }) }] };

			const playlists = Object.values(doc.playlists || {}).map(p => ({
				id: p.id, name: p.name,
				entryCount: p.entries?.length ?? 0,
				createdBy: p.createdBy,
				createdAt: p.createdAt,
			}));

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

	server.tool(
		"rtube_get_watch_party",
		"Get active watch party status",
		{
			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<TubeDoc>(tubeDocId(space));
			if (!doc?.watchParty) {
				return { content: [{ type: "text", text: JSON.stringify({ active: false }) }] };
			}

			return { content: [{ type: "text", text: JSON.stringify({ active: true, ...doc.watchParty }, null, 2) }] };
		},
	);
}
