// app/api/upload/route.ts
import { NextRequest } from 'next/server';

// Since using Multer directly is difficult with Next.js App Router,
// we'll create a custom implementation using busboy which multer uses internally

export async function POST(request: NextRequest) {
  try {
    // Check content type
    const contentType = request.headers.get('content-type') || '';
    if (!contentType.includes('multipart/form-data')) {
      return new Response(JSON.stringify({ error: 'Invalid content-type' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    // Use formData directly instead of trying to make multer work
    // This is the recommended approach for Next.js App Router
    const formData = await request.formData();
    const file = formData.get('file') as File;

    if (!file) {
      return new Response(JSON.stringify({ error: 'No file uploaded' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    // Here you can add file validation, processing, or storage
    // similar to what multer would do

    // Example: check file type or size
    if (buffer.length > 5 * 1024 * 1024) { // 5MB limit
      return new Response(JSON.stringify({ error: 'File too large' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    // Example: you can save the file to disk or cloud storage here
    // const fs = require('fs');
    // fs.writeFileSync(`./uploads/${file.name}`, buffer);

    return new Response(
      JSON.stringify({
        message: 'Upload successful',
        name: file.name,
        type: file.type,
        size: buffer.length,
      }),
      {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  } catch (err: any) {
    console.error('Upload error:', err);
    return new Response(JSON.stringify({ error: err.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}