import { NextResponse } from 'next/server'
import { slskdFetch } from '@/lib/slskd'
import { extractBestFiles, type SlskdRawResponse } from '@/lib/slskd-dedup'

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ searchId: string }> }
) {
  const { searchId } = await params

  try {
    const res = await slskdFetch(`/searches/${searchId}`)
    if (!res.ok) {
      throw new Error(`slskd results returned ${res.status}`)
    }

    const data = await res.json()
    const isComplete = data.state === 'Completed' || data.state === 'TimedOut'

    const responses: SlskdRawResponse[] = (data.responses || [])
      .filter((r: SlskdRawResponse) => r.files?.length > 0)

    const files = extractBestFiles(responses)

    return NextResponse.json({ files, isComplete })
  } catch (error) {
    console.error('Soulseek results error:', error)
    return NextResponse.json({ error: 'Failed to get results' }, { status: 502 })
  }
}
