import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { isRateLimited } from '@/lib/rate-limit'

export async function POST(req: NextRequest) {
  const ip =
    req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '0.0.0.0'

  if (isRateLimited(ip)) {
    return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 })
  }

  const body = await req.json().catch(() => null)

  if (
    !body?.url ||
    !body?.format ||
    !body?.quality ||
    body?.subtitles === undefined
  ) {
    return NextResponse.json(
      { error: 'Missing required fields: url, format, quality, subtitles' },
      { status: 400 }
    )
  }

  const download = await prisma.download.create({
    data: {
      url: String(body.url),
      format: String(body.format),
      quality: String(body.quality),
      subtitles: Boolean(body.subtitles),
      extraArgs: body.extraArgs ?? null,
      ipAddress: ip,
    },
  })

  return NextResponse.json({ uuid: download.uuid }, { status: 201 })
}
