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

export async function POST(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.email) {
    return NextResponse.json({ success: false, message: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await context.params
  const transferId = parseInt(id, 10)

  if (isNaN(transferId)) {
    return NextResponse.json({ success: false, message: 'Invalid ID' }, { status: 400 })
  }

  // Scoped to the sender: without this, any signed-in user could walk the
  // autoincrement IDs and make the app mail arbitrary recipients.
  const transfer = await prisma.transfer.findFirst({
    where: { id: transferId, senderEmail: session.user.email },
  })

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

  if (transfer.status !== 'ACTIVE') {
    return NextResponse.json({ success: false, message: 'Transfer is not active' }, { status: 400 })
  }

  if (transfer.expiresAt <= new Date()) {
    return NextResponse.json({ success: false, message: 'Transfer has expired' }, { status: 400 })
  }

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://transfertribe.com'
  const link = `${baseUrl}/download/${transfer.downloadUrl}`

  await sendMailjetEmail({
    to: transfer.recipientEmail,
    subject: 'Transfer resent: Your file is still available',
    text: `
${transfer.senderEmail} resent you a file via TransferTribe.

Link: ${link}

${transfer.message ? `Message:\n${transfer.message}\n\n` : ''}Note: You'll need the password they shared with you to download it.
`.trim(),
  })

  return NextResponse.json({ success: true, message: 'Resent successfully' })
}
