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

// PATCH /api/keys/[id] — toggle active status (revoke/reactivate)
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { id } = await params

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

  if (!key) {
    return NextResponse.json({ error: 'Chave não encontrada' }, { status: 404 })
  }

  const body = await req.json()
  const active = typeof body.active === 'boolean' ? body.active : !key.active

  const updated = await prisma.apiKey.update({
    where: { id },
    data: { active },
    select: { id: true, name: true, active: true },
  })

  return NextResponse.json(updated)
}

// DELETE /api/keys/[id] — permanently delete a key
export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { id } = await params

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

  if (!key) {
    return NextResponse.json({ error: 'Chave não encontrada' }, { status: 404 })
  }

  await prisma.apiKey.delete({ where: { id } })

  return NextResponse.json({ message: 'Chave revogada e excluída' })
}
