import { getMessages } from "@/lib/synap";
import type { ChatMessage } from "@/lib/types";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  try {
    const data = await getMessages(id, 100);

    const messages: ChatMessage[] = (data.messages ?? []).map((m) => ({
      id: m.id,
      role: m.user_id === "aeries" ? ("assistant" as const) : ("user" as const),
      content: m.content,
      timestamp: new Date(m.timestamp).getTime(),
    }));

    // Synap returns newest-first; reverse for chronological order
    messages.reverse();

    return Response.json({ messages });
  } catch {
    // New conversation with no messages yet — return empty
    return Response.json({ messages: [] });
  }
}
