import { NextResponse } from 'next/server';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';

export async function POST(request: Request) {
    try {
        const formData = await request.formData();
        const file = formData.get('file') as File;
        
        if (!file) {
            return NextResponse.json({ error: 'Tidak ada file yang diunggah' }, { status: 400 });
        }
        
        const bytes = await file.arrayBuffer();
        const buffer = Buffer.from(bytes);
        
        // Simpan ke folder public/uploads
        const uploadDir = path.join(process.cwd(), 'public', 'uploads');
        
        // Pastikan folder exists
        await mkdir(uploadDir, { recursive: true });
        
        // Buat nama file unik
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const fileExtension = path.extname(file.name);
        const cleanBaseName = path.basename(file.name, fileExtension).replace(/[^a-zA-Z0-9]/g, '-');
        const filename = `${cleanBaseName}-${uniqueSuffix}${fileExtension}`;
        const filePath = path.join(uploadDir, filename);
        
        // Tulis file ke disk
        await writeFile(filePath, buffer);
        
        return NextResponse.json({
            success: true,
            url: `/uploads/${filename}`
        });
    } catch (e: any) {
        return NextResponse.json({
            success: false,
            error: e.message
        }, { status: 500 });
    }
}
