/**
 * MCP tools for rPhotos (shared albums & annotations).
 *
 * Tools: rphotos_list_albums, rphotos_list_annotations
 */

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

export function registerPhotosTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rphotos_list_albums",
		"List shared photo albums 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<PhotosDoc>(photosDocId(space));
			if (!doc) return { content: [{ type: "text", text: JSON.stringify({ error: "No photos data found" }) }] };

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

	server.tool(
		"rphotos_list_annotations",
		"List photo annotations (notes on photos)",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			asset_id: z.string().optional().describe("Filter by asset ID"),
		},
		async ({ space, token, asset_id }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

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

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