/**
 * MCP tools for rBnb (community hospitality sharing).
 *
 * Tools: rbnb_list_listings, rbnb_get_listing, rbnb_list_stays, rbnb_list_endorsements
 */

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

export function registerBnbTools(server: McpServer, syncServer: SyncServer) {
	server.tool(
		"rbnb_list_listings",
		"List hospitality listings (rooms, couches, cabins, etc.)",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			type: z.string().optional().describe("Filter by type (couch, room, apartment, cabin, etc.)"),
			active_only: z.boolean().optional().describe("Only active listings (default true)"),
		},
		async ({ space, token, type, active_only }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

			let listings = Object.values(doc.listings || {});
			if (active_only !== false) listings = listings.filter(l => l.isActive);
			if (type) listings = listings.filter(l => l.type === type);

			const summary = listings.map(l => ({
				id: l.id, hostName: l.hostName, title: l.title,
				type: l.type, economy: l.economy,
				locationName: l.locationName, guestCapacity: l.guestCapacity,
				suggestedAmount: l.suggestedAmount, currency: l.currency,
				amenities: l.amenities, isActive: l.isActive,
			}));

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

	server.tool(
		"rbnb_get_listing",
		"Get full listing details with availability windows",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			listing_id: z.string().describe("Listing ID"),
		},
		async ({ space, token, listing_id }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

			const doc = syncServer.getDoc<BnbDoc>(bnbDocId(space));
			const listing = doc?.listings?.[listing_id];
			if (!listing) return { content: [{ type: "text", text: JSON.stringify({ error: "Listing not found" }) }] };

			const availability = Object.values(doc!.availability || {})
				.filter(a => a.listingId === listing_id);

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

	server.tool(
		"rbnb_list_stays",
		"List stay requests with status",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			status: z.string().optional().describe("Filter by status (pending, accepted, declined, completed, etc.)"),
		},
		async ({ space, token, status }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

			let stays = Object.values(doc.stays || {});
			if (status) stays = stays.filter(s => s.status === status);
			stays.sort((a, b) => b.requestedAt - a.requestedAt);

			const summary = stays.map(s => ({
				id: s.id, listingId: s.listingId,
				guestName: s.guestName, status: s.status,
				checkIn: s.checkIn, checkOut: s.checkOut,
				guestCount: s.guestCount, messageCount: s.messages?.length ?? 0,
				requestedAt: s.requestedAt,
			}));

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

	server.tool(
		"rbnb_list_endorsements",
		"List endorsements (reviews) between hosts and guests",
		{
			space: z.string().describe("Space slug"),
			token: z.string().optional().describe("JWT auth token"),
			listing_id: z.string().optional().describe("Filter by listing ID"),
			limit: z.number().optional().describe("Max results (default 50)"),
		},
		async ({ space, token, listing_id, limit }) => {
			const access = await resolveAccess(token, space, false);
			if (!access.allowed) return accessDeniedResponse(access.reason!);

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

			let endorsements = Object.values(doc.endorsements || {});
			if (listing_id) endorsements = endorsements.filter(e => e.listingId === listing_id);
			endorsements.sort((a, b) => b.createdAt - a.createdAt);
			endorsements = endorsements.slice(0, limit || 50);

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