import { requireSession } from '@/lib/session' import { restoreAgent } from '@/lib/oauth' import { getBlockEvent } from '@/lib/lexicon' import { fetchEngagementByAtUri } from '@/lib/engagement' // GET /api/blocks/refresh?rkey=... // Re-fetches engagement for the original post and returns accounts that have // engaged since the block was created (i.e. not already in blockedDids or failedDids). export async function GET(request: Request) { const { searchParams } = new URL(request.url) const rkey = searchParams.get('rkey') if (!rkey) return Response.json({ error: 'rkey is required' }, { status: 400 }) let session: { did: string } try { session = await requireSession() } catch { return Response.json({ error: 'Not authenticated' }, { status: 401 }) } try { const agent = await restoreAgent(session.did) const { record } = await getBlockEvent(agent, session.did, rkey) if (!record.sourcePostUri) { return Response.json( { error: 'Source post URI not recorded for this event' }, { status: 400 } ) } if (record.undoneAt) { return Response.json( { error: 'Cannot refresh an undone block event' }, { status: 400 } ) } // Build the exclusion set — accounts already processed const alreadyProcessed = new Set([ ...(record.blockedDids ?? []), ...(record.failedDids ?? []), ...(record.pendingDids ?? []), ]) // Re-fetch engagement using the stored AT URI and original criteria const { post, accounts } = await fetchEngagementByAtUri( record.sourcePostUri, session.did, record.criteria ) // Filter to only accounts not yet processed const newAccounts = accounts.filter((a) => !alreadyProcessed.has(a.profile.did)) return Response.json({ post, newAccounts, checkedAt: new Date().toISOString(), totalFound: accounts.length, alreadyProcessed: alreadyProcessed.size, }) } catch (err) { console.error('[api/blocks/refresh]', err) return Response.json({ error: 'Failed to refresh engagement' }, { status: 500 }) } }