import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

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

  const download = await prisma.download.findUnique({
    where: { uuid },
    include: {
      tokens: { orderBy: { createdAt: 'desc' }, take: 1 },
    },
  })

  if (!download) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 })
  }

  const latestToken = download.tokens[0]
  const validToken =
    latestToken && latestToken.expiresAt > new Date() ? latestToken : null

  return NextResponse.json({
    uuid: download.uuid,
    status: download.status,
    format: download.format,
    quality: download.quality,
    subtitles: download.subtitles,
    fileName: download.fileName,
    fileSize: download.fileSize?.toString() ?? null,
    errorMsg: download.errorMsg,
    submittedAt: download.submittedAt,
    completedAt: download.completedAt,
    downloadToken: download.status === 'DONE' ? (validToken?.token ?? null) : null,
    tokenExpiresAt: download.status === 'DONE' ? (validToken?.expiresAt ?? null) : null,
  })
}
