import { type NextRequest, NextResponse } from "next/server" const WEBHOOK_URL = "https://n8n.biohazardvfx.com/webhook/d2ab4653-a107-412c-a905-ccd80e5b76cd" export async function POST(request: NextRequest) { try { const body = await request.json() if (typeof body !== "object" || body === null) { return NextResponse.json({ error: "Invalid request body" }, { status: 400 }) } const { message, timestamp, sessionId } = body as { message?: string timestamp?: string sessionId?: string } if (!message || typeof message !== "string") { return NextResponse.json({ error: "Message is required" }, { status: 400 }) } if (!message) { return NextResponse.json({ error: "Message is required" }, { status: 400 }) } console.log("[v0] Sending to webhook:", { message, timestamp, sessionId }) const response = await fetch(WEBHOOK_URL, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ message, timestamp, sessionId, }), }) console.log("[v0] Webhook response status:", response.status) const responseText = await response.text() console.log("[v0] Webhook response body (first 200 chars):", responseText.substring(0, 200)) if (!response.ok) { // Try to parse as JSON if possible, otherwise use text let errorData try { errorData = responseText ? JSON.parse(responseText) : {} } catch { errorData = { message: responseText || "Unknown error" } } console.error("[v0] Webhook error:", errorData) return NextResponse.json( { error: errorData.message || "Failed to communicate with webhook", hint: errorData.hint, code: errorData.code, }, { status: response.status }, ) } if (!responseText) { console.log("[v0] Empty response from webhook") return NextResponse.json({ response: "The webhook received your message but didn't return a response. Please ensure your n8n workflow includes a 'Respond to Webhook' node that returns data.", hint: "Add a 'Respond to Webhook' node in your n8n workflow to send responses back to the chat.", }) } try { // Split response by newlines to get individual JSON objects const lines = responseText.trim().split("\n") const chunks: string[] = [] for (const line of lines) { if (!line.trim()) continue try { const chunk = JSON.parse(line) // Extract content from "item" type chunks if (chunk.type === "item" && chunk.content) { chunks.push(chunk.content) } } catch { console.log("[v0] Failed to parse line:", line) } } // Combine all chunks into a single message if (chunks.length > 0) { const fullMessage = chunks.join("") console.log("[v0] Combined message from", chunks.length, "chunks") return NextResponse.json({ response: fullMessage }) } // If no chunks found, try parsing as regular JSON const data = JSON.parse(responseText) console.log("[v0] Parsed webhook data:", data) // Extract the response from various possible fields let responseMessage = data.response || data.message || data.output || data.text // If the response is an object, try to extract from nested fields if (typeof responseMessage === "object") { responseMessage = responseMessage.response || responseMessage.message || responseMessage.output || responseMessage.text } // If still no message found, stringify the entire response if (!responseMessage) { responseMessage = JSON.stringify(data) } return NextResponse.json({ response: responseMessage }) } catch { console.log("[v0] Response is not JSON, returning as text") // If not JSON, return the text as the response return NextResponse.json({ response: responseText }) } } catch (error) { console.error("[v0] API route error:", error) return NextResponse.json({ error: "Internal server error" }, { status: 500 }) } }