import { NextRequest, NextResponse } from "next/server";
import { sendMessage } from "@/lib/agent-client";

export async function POST(request: NextRequest) {
  const userEmail =
    request.headers.get("x-forwarded-email") ||
    process.env.DEV_USER_EMAIL ||
    "developer@localhost";

  let body: { text: string; conversation_id?: string };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  if (!body.text || typeof body.text !== "string") {
    return NextResponse.json(
      { error: "Missing required field: text" },
      { status: 400 }
    );
  }

  try {
    const result = await sendMessage(body.text, userEmail, body.conversation_id);
    return NextResponse.json(result);
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 502 });
  }
}
