import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export const runtime = 'nodejs';

export async function POST(req: NextRequest) {
  try {
    const form = await req.formData();
    const file = form.get('file') as File | null;
    if (!file) {
      return NextResponse.json({ error: 'File tidak ditemukan' }, { status: 400 });
    }
    const type = file.type || '';
    if (!type.startsWith('image/')) {
      return NextResponse.json({ error: 'Hanya gambar yang diperbolehkan' }, { status: 400 });
    }
    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    if (buffer.length > 5 * 1024 * 1024) {
      return NextResponse.json({ error: 'Ukuran gambar maksimal 5MB' }, { status: 400 });
    }

    const uploadsDir = path.join(process.cwd(), 'public', 'uploads');
    await fs.promises.mkdir(uploadsDir, { recursive: true });
    const ext = path.extname(file.name) || (type.includes('png') ? '.png' : type.includes('jpeg') ? '.jpg' : '');
    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`;
    const filePath = path.join(uploadsDir, filename);
    await fs.promises.writeFile(filePath, buffer);
    const publicPath = `/uploads/${filename}`;
    return NextResponse.json({ path: publicPath });
  } catch (err: any) {
    return NextResponse.json({ error: 'Upload gagal', message: err?.message }, { status: 500 });
  }
}