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

export async function POST(req: NextRequest) {
  const formData = await req.formData()
  const file = formData.get('file') as File

  if (!file) {
    return NextResponse.json({ error: 'No file provided' }, { status: 400 })
  }

  try {
    const arrayBuffer = await file.arrayBuffer()
    const buffer = new Uint8Array(arrayBuffer)

    const fileName = `${Date.now()}-${file.name}`
    const filePath = path.join(process.cwd(), 'public', 'imgs', fileName)

    await writeFile(filePath, buffer)

    const fileUrl = `/imgs/${fileName}` // caminho relativo acessível pela tag <img src=...>

    return NextResponse.json({ url: fileUrl })
  } catch (error) {
    console.error('Upload failed:', error)
    return NextResponse.json({ error: 'Upload failed' }, { status: 500 })
  }
}
