import { writeFile, mkdir } from "fs/promises"; import { NextRequest, NextResponse } from "next/server"; import path from "path"; import { v4 as uuidv4 } from "uuid"; export async function POST(req: NextRequest) { const formData = await req.formData(); const files = formData.getAll("file") as File[]; if (!files || files.length === 0) { return NextResponse.json({ error: "No files provided" }, { status: 400 }); } const urls: string[] = []; let type = "IMAGE"; // Check types const hasVideo = files.some(f => f.type.startsWith("video/")); const hasImage = files.some(f => f.type.startsWith("image/")); if (files.length > 1) { type = "CAROUSEL"; } else if (hasVideo) { type = "VIDEO"; } // Ensure upload dir const uploadDir = path.join(process.cwd(), "public", "uploads"); await mkdir(uploadDir, { recursive: true }); for (const file of files) { const buffer = Buffer.from(await file.arrayBuffer()); const ext = path.extname(file.name) || (file.type.startsWith("image") ? ".jpg" : ".mp4"); const filename = `${uuidv4()}${ext}`; const filepath = path.join(uploadDir, filename); await writeFile(filepath, buffer); // In production we'd upload to S3/Cloudinary and return that URL. // For local dev, we serve from public/uploads. // Note: Graph API requires PUBLICLY ACCESSIBLE URLs. // If running on localhost, Instagram server CANNOT fetch this. // CRITICAL: We need ngrok or similar for Instagram Graph API to fetch media. // Or we upload to a public bucket. // I will note this limitation. urls.push(`/uploads/${filename}`); } return NextResponse.json({ urls, type }); }