import { prisma } from "@/app/lib/prisma"
import { NextResponse } from "next/server"

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const agentId = searchParams.get("agentId")

  if (!agentId) {
    return NextResponse.json({ error: "agentId is required" }, { status: 400 })
  }

  const conversations = await prisma.conversation.findMany({
    where: { agentId: parseInt(agentId) },
    orderBy: { updatedAt: "desc" },
    include: {
      messages: {
        orderBy: { timestamp: "asc" },
        take: 1,
      },
    },
  })

  return NextResponse.json(conversations)
}

export async function POST(request: Request) {
  const body = await request.json()
  const { agentId, title } = body

  if (!agentId) {
    return NextResponse.json({ error: "agentId is required" }, { status: 400 })
  }

  const conversation = await prisma.conversation.create({
    data: {
      agentId: parseInt(agentId),
      title: title || "新对话",
    },
  })

  return NextResponse.json(conversation)
}
