import { NextResponse } from 'next/server'
import { slskdFetch } from '@/lib/slskd'

export async function POST(request: Request) {
  try {
    const { username, files } = await request.json()
    if (!username || !files?.length) {
      return NextResponse.json({ error: 'username and files required' }, { status: 400 })
    }

    const res = await slskdFetch(`/transfers/downloads/${encodeURIComponent(username)}`, {
      method: 'POST',
      body: JSON.stringify(files.map((f: { filename: string; size: number }) => ({
        filename: f.filename,
        size: f.size,
      }))),
    })

    if (!res.ok) {
      throw new Error(`slskd download returned ${res.status}`)
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Soulseek download error:', error)
    return NextResponse.json({ error: 'Download request failed' }, { status: 502 })
  }
}
