import { writeFile, mkdir } from 'fs/promises'
import { NextRequest, NextResponse } from 'next/server'
import { join } from 'path'

export async function POST(request: NextRequest) {
  try {
    const data = await request.formData()
    const file: File | null = data.get('file') as unknown as File

    if (!file) {
      return NextResponse.json({ success: false })
    }

    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)

    // Define the directory path
    const directoryPath = join(process.cwd(), 'tmp')

    // Ensure the directory exists
    await mkdir(directoryPath, { recursive: true })

    const filePath = join(directoryPath, file.name)

    await writeFile(filePath, buffer)
    console.log(`open ${filePath} to see the uploaded file `)

    return NextResponse.json({
      success: true,
      path: filePath,
      fileName: file.name,  
    })
  } catch (err) {
    console.log({ err })
    return NextResponse.json({ success: false })
  }
}
