/** * POST /api/parse-docx * * Accepts a .docx file upload, parses it, and returns the paragraphs * with their text and formatting info. Stores the buffer for later use. */ import { NextResponse } from "next/server"; import { parseDocx } from "@/lib/docx-service"; import fileStore from "@/lib/file-store"; import { v4 as uuidv4 } from "uuid"; export async function POST(request) { try { const formData = await request.formData(); const file = formData.get("file"); if (!file) { return NextResponse.json( { error: "No file provided" }, { status: 400 } ); } if ( !file.name.endsWith(".docx") && file.type !== "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) { return NextResponse.json( { error: "Only .docx files are supported" }, { status: 400 } ); } const arrayBuffer = await file.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); const { paragraphs } = parseDocx(buffer); // Generate a session ID and store the buffer const sessionId = uuidv4(); fileStore.save(sessionId, { originalBuffer: buffer, fileName: file.name, paragraphs: paragraphs, enrichedBuffer: null, headingIndices: [], }); return NextResponse.json({ sessionId, fileName: file.name, paragraphs: paragraphs.map((p) => ({ index: p.index, text: p.text, fontSizePt: p.fontSizePt, isBold: p.isBold, styleId: p.styleId, })), totalParagraphs: paragraphs.length, }); } catch (err) { console.error("Parse error:", err); return NextResponse.json( { error: "Failed to parse document: " + err.message }, { status: 500 } ); } }