export const runtime = 'nodejs'
import { NextResponse } from 'next/server'
import { PrismaClient } from '@/app/generated/prisma'

export async function GET(request: Request) {
  const prisma = new PrismaClient()
  try {
    const { searchParams } = new URL(request.url)
    const limitRaw = searchParams.get('limit')
    let limit = Number(limitRaw ?? '10')
    if (!Number.isFinite(limit) || limit <= 0) limit = 100
    if (limit > 1000) limit = 1000

    const rows = await prisma.content.findMany({
      where: { handleId: null },
      select: { id: true },
      take: limit,
      orderBy: { pubDate: 'desc' },
    })
    const ids = rows.map(r => r.id)
    console.log(`[contents/handleupdate] fetched ${ids.length}/${limit} ids without handle`)
    // Call local parsingServer with body { ids }
    try {
      const upstream = await fetch('http://localhost:9556/gethandle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids }),
      })
      const text = await upstream.text()
      let forwarded: any = null
      try { forwarded = text ? JSON.parse(text) : null } catch { forwarded = { message: text } }
      // Map handles back to Content rows
      let mapped = 0
      const failures: Array<{ id: string, reason: string }> = []
      if (forwarded?.success && Array.isArray(forwarded?.items)) {
        for (const item of forwarded.items as Array<{ id?: string, handle?: string, avatar?: string }>) {
          const cid = String(item?.id ?? '')
          let h = String(item?.handle ?? '').trim()
          const avatar = typeof item?.avatar === 'string' ? item.avatar : undefined
          if (!cid || !h) { if (cid) failures.push({ id: cid, reason: 'missing_handle' }); continue }
          try {
            const handleRow = await prisma.handle.upsert({
              where: { handle: h },
              update: { ...(avatar ? { avatar } : {}) },
              create: { handle: h, ...(avatar ? { avatar } : {}) },
              select: { id: true }
            })
            await prisma.content.update({
              where: { id: cid },
              data: { handle: { connect: { id: handleRow.id } } },
            })
            mapped += 1
          } catch (e) {
            failures.push({ id: cid, reason: 'db_update_failed' })
            console.error('[contents/handleupdate] map failed for', cid, e)
          }
        }
      }
      return NextResponse.json({ success: true, count: ids.length, ids, mapped, failures, upstream: forwarded }, { status: upstream.status })
    } catch (e) {
      console.error('[contents/handleupdate] upstream call error:', e)
      return NextResponse.json({ success: true, count: ids.length, ids, upstream: { error: 'upstream failed' } })
    }
  } catch (e) {
    console.error('[contents/handleupdate] query error:', e)
    return NextResponse.json({ error: 'query failed' }, { status: 500 })
  } finally {
    try { await (prisma as any).$disconnect() } catch {}
  }
}


