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

export async function GET(
  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 upload = await prisma.upload.findFirst({
    where: { id, userId: session.user.id },
  })

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

  const url = await getSignedUrl(upload.key)
  return NextResponse.redirect(url)
}

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 upload = await prisma.upload.findFirst({
    where: { id, userId: session.user.id },
  })

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

  try {
    await deleteFile(upload.key)
  } catch (error) {
    console.error('S3 delete error:', error)
    // Continue with DB deletion even if S3 fails
  }

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

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