import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/prisma' import { auth } from '@/auth' export async function GET(req: NextRequest) { try { const session = await auth() if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) const canvasId = req.nextUrl.searchParams.get('id') if (!canvasId) return NextResponse.json({ error: 'Missing id' }, { status: 400 }) const canvas = await prisma.canvas.findUnique({ where: { id: canvasId, userId: session.user.id }, }) if (!canvas) return NextResponse.json({ error: 'Not found' }, { status: 404 }) let parsed: any try { parsed = JSON.parse(canvas.data) } catch { return NextResponse.json({ error: 'Invalid data' }, { status: 500 }) } if (parsed.type !== 'pptx' || !parsed.base64) { return NextResponse.json({ error: 'Not a PPTX canvas' }, { status: 400 }) } const byteChars = atob(parsed.base64) const bytes = new Uint8Array(byteChars.length) for (let i = 0; i < byteChars.length; i++) bytes[i] = byteChars.charCodeAt(i) const filename = parsed.filename || `${canvas.name.replace(/[^a-zA-Z0-9]/g, '_')}.pptx` // Auto-delete after serving await prisma.canvas.delete({ where: { id: canvasId } }) return new NextResponse(bytes, { headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'Content-Disposition': `attachment; filename="${filename}"`, 'Content-Length': String(bytes.length), }, }) } catch (error) { console.error('[Canvas Download]', error) return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }) } }