import { NextRequest, NextResponse } from 'next/server'
import { createReadStream, statSync } from 'fs'
import path from 'path'
import { validateToken } from '@/lib/token'
import { prisma } from '@/lib/prisma'

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ token: string }> }
) {
  const { token } = await params
  const result = await validateToken(token)

  if (!result) {
    return NextResponse.json({ error: 'Invalid or expired token' }, { status: 404 })
  }

  const { filePath } = result

  let stat: ReturnType<typeof statSync>
  try {
    stat = statSync(filePath)
  } catch {
    return NextResponse.json({ error: 'File not found on server' }, { status: 404 })
  }

  await prisma.downloadToken.update({
    where: { token },
    data: { usedAt: new Date() },
  })

  const fileName = path.basename(filePath)
  const stream = createReadStream(filePath)

  return new NextResponse(stream as unknown as ReadableStream, {
    headers: {
      'Content-Disposition': `attachment; filename="${fileName}"`,
      'Content-Length': String(stat.size),
      'Content-Type': 'application/octet-stream',
    },
  })
}
