import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ chatId: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { chatId } = await params

  // Verify ownership
  const chat = await prisma.chat.findFirst({
    where: { id: chatId, userId: session.user.id },
  })

  if (!chat) {
    return NextResponse.json({ error: 'Chat não encontrado' }, { status: 404 })
  }

  const messages = await prisma.chatMessage.findMany({
    where: { chatId },
    orderBy: { createdAt: 'asc' },
    select: {
      id: true,
      role: true,
      content: true,
      createdAt: true,
    },
  })

  return NextResponse.json({ messages })
}

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ chatId: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { chatId } = await params

  const chat = await prisma.chat.findFirst({
    where: { id: chatId, userId: session.user.id },
  })

  if (!chat) {
    return NextResponse.json({ error: 'Chat não encontrado' }, { status: 404 })
  }

  await prisma.chat.delete({ where: { id: chatId } })

  return NextResponse.json({ success: true })
}
