import { s3 } from '@/lib/cloudflare'
import { PutObjectCommand } from '@aws-sdk/client-s3'
import { NextRequest, NextResponse } from 'next/server'

// const s3Client = new S3Client({
//   region: 'auto',
//   endpoint: process.env.NEXT_PUBLIC_CLOUDFLARE_ACCESS_ENDPOINT,
//   credentials: {
//     accessKeyId: process.env.NEXT_PUBLIC_CLOUDFLARE_ACCESS_KEY_ID!,
//     secretAccessKey: process.env.NEXT_PUBLIC_CLOUDFLARE_SECRET_ACCESS_KEY!,
//   },
// })

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 })
  }

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

  const fileName = `${Date.now()}-${file.name}`

  try {
    await s3.send(
      new PutObjectCommand({
        Bucket: process.env.NEXT_PUBLIC_CLOUDFLARE_BUCKET!,
        Key: fileName,
        Body: buffer,
        ContentType: file.type,
      }),
    )

    const fileUrl = `https://${process.env.NEXT_PUBLIC_CLOUDFLARE_URL_PUBLIC_BUCKET}/${fileName}`

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