import { NextRequest, NextResponse } from 'next/server' import prisma from '@/lib/prisma' import { auth } from '@/auth' /** * GET /api/notes/[id]/live-block-refs * Notes that embed a living block sourced from this note. */ export async function GET( _req: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const session = await auth() if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { id: sourceNoteId } = await params const sourceNote = await prisma.note.findFirst({ where: { id: sourceNoteId, userId: session.user.id }, select: { id: true }, }) if (!sourceNote) { return NextResponse.json({ error: 'Note not found' }, { status: 404 }) } const refs = await prisma.liveBlockRef.findMany({ where: { sourceNoteId }, orderBy: { createdAt: 'desc' }, select: { id: true, blockId: true, targetNoteId: true, createdAt: true, targetNote: { select: { id: true, title: true, notebookId: true, }, }, }, }) const notebookIds = [...new Set( refs.map(r => r.targetNote.notebookId).filter(Boolean) as string[] )] const notebooks = notebookIds.length > 0 ? await prisma.notebook.findMany({ where: { id: { in: notebookIds }, userId: session.user.id }, select: { id: true, name: true }, }) : [] const notebookMap = Object.fromEntries(notebooks.map(nb => [nb.id, nb.name])) const uniqueTargets = new Map() for (const ref of refs) { const existing = uniqueTargets.get(ref.targetNoteId) if (existing) { if (!existing.blockIds.includes(ref.blockId)) { existing.blockIds.push(ref.blockId) } continue } uniqueTargets.set(ref.targetNoteId, { targetNoteId: ref.targetNoteId, targetNoteTitle: ref.targetNote.title || '', notebookName: ref.targetNote.notebookId ? (notebookMap[ref.targetNote.notebookId] || '') : '', blockIds: [ref.blockId], createdAt: ref.createdAt.toISOString(), }) } return NextResponse.json({ refs: Array.from(uniqueTargets.values()), total: uniqueTargets.size, }) }