import { NextRequest, NextResponse } from "next/server";
import { getAgent } from "@/lib/agent-registry";
import { createChannelClient } from "@/lib/channel-client";

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ agent: string }> }
) {
  const { agent: agentName } = await params;
  const agent = await getAgent(agentName);
  if (!agent) {
    return NextResponse.json({ error: "Agent not found" }, { status: 404 });
  }

  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 client = createChannelClient(agent.channelUrl, agent.secret);
    const result = await client.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 });
  }
}
