import { NextResponse } from "next/server";
import { runSiteMenteText } from "../../../../lib/ai/siteMenteAgent";

type MessagePayload = {
  role: "user" | "assistant" | "system";
  content: string;
};

const isValidMessage = (message: MessagePayload) => {
  return (
    message &&
    typeof message.content === "string" &&
    ["user", "assistant", "system"].includes(message.role)
  );
};

export const runtime = "nodejs";

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as { messages?: MessagePayload[] };

    if (!Array.isArray(body.messages) || body.messages.length === 0) {
      return NextResponse.json(
        { error: "messages array is required." },
        { status: 400 }
      );
    }

    if (!body.messages.every(isValidMessage)) {
      return NextResponse.json(
        { error: "messages must include role and content." },
        { status: 400 }
      );
    }

    const { reply } = await runSiteMenteText({ messages: body.messages });
    return NextResponse.json({ reply });
  } catch (error) {
    console.error("[SiteMente][API] Text route failed", error);
    return NextResponse.json(
      { error: "Failed to generate response." },
      { status: 500 }
    );
  }
}
