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 (err) {
    const msg = err instanceof Error ? err.message : String(err);
    // Log the actual error so Synap outages are visible in server logs
    if (!msg.includes("404")) {
      console.error(`[synap] failed to load messages for conversation ${id.slice(0, 8)}…: ${msg}`);
    }
    return Response.json({ messages: [] });
  }
}
