import { prisma } from '@/lib/prisma'
import { NextResponse } from 'next/server'
import { TransferStatus } from '@prisma/client'

/**
 * Pre-authentication metadata for the download page.
 *
 * This runs BEFORE the visitor has proved they know the password, so it returns
 * only what the landing screen needs to render. Filenames, the sender's
 * message, the recipient address and the on-disk file paths are withheld until
 * /api/verify succeeds.
 */
export async function GET(req: Request) {
  const url = new URL(req.url)
  const id = url.searchParams.get('id')

  if (!id) {
    return NextResponse.json({ success: false, message: 'No ID provided' }, { status: 400 })
  }

  const transfer = await prisma.transfer.findUnique({
    where: { downloadUrl: id },
    include: { files: true },
  })

  if (!transfer) {
    return NextResponse.json({ success: false, message: 'Transfer not found' }, { status: 404 })
  }

  const isExpired = transfer.expiresAt <= new Date()

  if (transfer.status !== TransferStatus.ACTIVE || isExpired) {
    return NextResponse.json(
      { success: false, message: 'This transfer is no longer available' },
      { status: 410 }
    )
  }

  const totalSize = transfer.files.reduce((sum, file) => sum + file.size, BigInt(0))

  return NextResponse.json({
    success: true,
    transfer: {
      senderEmail: transfer.senderEmail,
      fileCount: transfer.files.length,
      totalSize: Number(totalSize),
      expiresAt: transfer.expiresAt.toISOString(),
      requiresPassword: Boolean(transfer.passwordHash),
    },
  })
}
