import { NextRequest, NextResponse } from "next/server";
import { getFilteredProperties, getPropertyBySlug } from "@/lib/services/property.service";
import { formatNaira } from "@/lib/utils";

export const dynamic = "force-dynamic";

const MCP_TOOLS = [
  {
    name: "search_properties",
    description: "Search verified real estate listings across Nigeria (Lagos, Abuja, Rivers, Oyo, etc.) with price, location, and title filters.",
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description: "Search term or neighborhood (e.g. 'Lekki Phase 1', 'Maitama', 'Banana Island')",
        },
        type: {
          type: "string",
          enum: ["FOR_SALE", "FOR_RENT", "SHORTLET"],
          description: "Listing transaction type",
        },
        state: {
          type: "string",
          description: "Nigerian state ID (e.g. 'lagos', 'abuja', 'rivers', 'oyo')",
        },
        propertyType: {
          type: "string",
          enum: ["HOUSE", "APARTMENT", "LAND", "COMMERCIAL"],
          description: "Type of real estate",
        },
        minPrice: {
          type: "number",
          description: "Minimum budget in Naira (NGN ₦)",
        },
        maxPrice: {
          type: "number",
          description: "Maximum budget in Naira (NGN ₦)",
        },
        page: {
          type: "number",
          description: "Page number (default: 1)",
        },
      },
    },
  },
  {
    name: "get_property_detail",
    description: "Retrieve complete details, title documentation, pricing, agent contact, and coordinates for a property using its slug or reference code.",
    inputSchema: {
      type: "object",
      properties: {
        slugOrRef: {
          type: "string",
          description: "Property SEO slug (e.g. 'luxury-duplex-in-lekki-ng-la-1234') or reference code (e.g. 'NG-LA-1234')",
        },
      },
      required: ["slugOrRef"],
    },
  },
];

export async function GET() {
  return NextResponse.json({
    name: "nigerialisting-mcp-server",
    version: "1.0.0",
    protocolVersion: "2024-11-05",
    description: "Model Context Protocol (MCP) server for Nigeria Listing - Verified Nigerian Real Estate Marketplace",
    capabilities: {
      tools: {},
    },
    tools: MCP_TOOLS,
  });
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { method, params, id = "1" } = body;

    if (method === "tools/list") {
      return NextResponse.json({
        jsonrpc: "2.0",
        id,
        result: {
          tools: MCP_TOOLS,
        },
      });
    }

    if (method === "tools/call") {
      const toolName = params?.name;
      const toolArgs = params?.arguments || {};

      if (toolName === "search_properties") {
        const filters: Record<string, string | undefined> = {};
        if (toolArgs.query) filters.q = String(toolArgs.query);
        if (toolArgs.type) filters.type = String(toolArgs.type);
        if (toolArgs.state) filters.state = String(toolArgs.state);
        if (toolArgs.propertyType) filters.propertyType = String(toolArgs.propertyType);
        if (toolArgs.minPrice) filters.minPrice = String(toolArgs.minPrice);
        if (toolArgs.maxPrice) filters.maxPrice = String(toolArgs.maxPrice);

        const page = Number(toolArgs.page) || 1;
        const catalogResult = await getFilteredProperties(filters, page, 10);

        const formattedProperties = catalogResult.properties.map((p) => ({
          title: p.title,
          referenceCode: p.reference_code,
          price: formatNaira(p.price),
          type: p.listing_type,
          location: p.location,
          state: p.state?.name,
          titleType: p.title_type,
          bedrooms: p.bedrooms,
          bathrooms: p.bathrooms,
          url: `https://nigerialisting.vercel.app/properties/${p.slug}`,
        }));

        return NextResponse.json({
          jsonrpc: "2.0",
          id,
          result: {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    totalFound: catalogResult.totalCount,
                    page,
                    properties: formattedProperties,
                  },
                  null,
                  2
                ),
              },
            ],
          },
        });
      }

      if (toolName === "get_property_detail") {
        const slugOrRef = toolArgs.slugOrRef;
        if (!slugOrRef) {
          return NextResponse.json({
            jsonrpc: "2.0",
            id,
            error: { code: -32602, message: "Missing required argument 'slugOrRef'" },
          });
        }

        const property = await getPropertyBySlug(String(slugOrRef));
        if (!property) {
          return NextResponse.json({
            jsonrpc: "2.0",
            id,
            result: {
              content: [
                {
                  type: "text",
                  text: `Property with reference or slug "${slugOrRef}" was not found on Nigeria Listing.`,
                },
              ],
            },
          });
        }

        const summary = {
          title: property.title,
          referenceCode: property.reference_code,
          price: formatNaira(property.price),
          type: property.listing_type,
          propertyType: property.property_type,
          location: property.location,
          state: property.state?.name,
          lga: property.lga?.name,
          titleType: property.title_type,
          description: property.description,
          bedrooms: property.bedrooms,
          bathrooms: property.bathrooms,
          isVerified: property.is_verified,
          url: `https://nigerialisting.vercel.app/properties/${property.slug}`,
        };

        return NextResponse.json({
          jsonrpc: "2.0",
          id,
          result: {
            content: [
              {
                type: "text",
                text: JSON.stringify(summary, null, 2),
              },
            ],
          },
        });
      }

      return NextResponse.json({
        jsonrpc: "2.0",
        id,
        error: { code: -32601, message: `Unknown tool "${toolName}"` },
      });
    }

    return NextResponse.json({
      jsonrpc: "2.0",
      id,
      error: { code: -32600, message: `Unsupported method "${method}"` },
    });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "Internal MCP Error";
    return NextResponse.json(
      {
        jsonrpc: "2.0",
        error: { code: -32603, message: msg },
      },
      { status: 500 }
    );
  }
}
