import { v2 as cloudinary } from "cloudinary"
import { NextRequest, NextResponse } from "next/server"

cloudinary.config({
  cloud_name: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
  api_key: process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
})

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

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

  const productId = formData.get("productId") as string | null
  const rawPosition = formData.get("position") as string | null

  // Build a structured public_id when productId + position are provided.
  // position 0 → …/main, position N → …/gallery-N
  let publicId: string | undefined
  let assetFolder: string | undefined
  if (productId && rawPosition !== null) {
    const position = parseInt(rawPosition, 10)
    const slot = position === 0 ? "main" : `gallery-${position}`
    publicId = `the-pet-loft/products/${productId}/${slot}`
    assetFolder = `the-pet-loft/products/${productId}`
  }

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

  try {
    const result = await new Promise<{ secure_url: string }>((resolve, reject) => {
      cloudinary.uploader
        .upload_stream(
          { public_id: publicId, asset_folder: assetFolder, resource_type: "image", overwrite: true },
          (error, res) => {
            if (error || !res) reject(error ?? new Error("Upload failed"))
            else resolve(res as { secure_url: string })
          },
        )
        .end(buffer)
    })

    return NextResponse.json({ url: result.secure_url })
  } catch (err) {
    const message = err instanceof Error ? err.message : "Upload failed"
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
