import { NextRequest, NextResponse } from 'next/server' import prisma from '@/lib/prisma' import { auth } from '@/auth' import fs from 'fs' export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string; attachmentId: string }> } ) { const session = await auth() if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } try { const { id: noteId, attachmentId } = await params const download = request.nextUrl.searchParams.get('download') const attachment = await prisma.noteAttachment.findFirst({ where: { id: attachmentId, noteId, note: { userId: session.user.id } }, include: download ? undefined : { chunks: { select: { id: true, chunkIndex: true, pageNumber: true }, orderBy: { chunkIndex: 'asc' }, }, }, }) if (!attachment) { return NextResponse.json({ error: 'Not found' }, { status: 404 }) } if (download) { if (!fs.existsSync(attachment.filePath)) { return NextResponse.json({ error: 'File not found' }, { status: 404 }) } const fileBuffer = fs.readFileSync(attachment.filePath) return new NextResponse(fileBuffer, { headers: { 'Content-Type': attachment.mimeType || 'application/pdf', 'Content-Disposition': `inline; filename="${attachment.fileName}"`, }, }) } return NextResponse.json({ success: true, data: attachment }) } catch (error) { console.error('Error fetching attachment:', error) return NextResponse.json({ error: 'Failed to fetch attachment' }, { status: 500 }) } } export async function DELETE( request: NextRequest, { params }: { params: Promise<{ id: string; attachmentId: string }> } ) { const session = await auth() if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } try { const { id: noteId, attachmentId } = await params const attachment = await prisma.noteAttachment.findFirst({ where: { id: attachmentId, noteId, note: { userId: session.user.id } }, }) if (!attachment) { return NextResponse.json({ error: 'Not found' }, { status: 404 }) } try { if (fs.existsSync(attachment.filePath)) { fs.unlinkSync(attachment.filePath) } } catch {} await prisma.noteAttachment.delete({ where: { id: attachmentId } }) return NextResponse.json({ success: true }) } catch (error) { console.error('Error deleting attachment:', error) return NextResponse.json({ error: 'Failed to delete attachment' }, { status: 500 }) } }