import { NextRequest, NextResponse } from 'next/server'
import { writeFile, mkdir } from 'fs/promises'
import path from 'path'

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const productId = formData.get('productId') as string
    const images = formData.getAll('images') as File[]

    if (!productId || images.length === 0) {
      return NextResponse.json(
        { error: 'Product ID and images are required' },
        { status: 400 }
      )
    }

    const uploadDir = path.join(process.cwd(), 'public', 'images', 'products')
    
    // Ensure directory exists
    try {
      await mkdir(uploadDir, { recursive: true })
    } catch (error) {
      // Directory might already exist, ignore error
    }

    const uploadedFilenames: string[] = []

    // Get existing images count for this product to determine next index
    const existingImages = await getExistingImageCount(parseInt(productId))
    let imageIndex = existingImages + 1

    for (const image of images) {
      const bytes = await image.arrayBuffer()
      const buffer = Buffer.from(bytes)

      // Generate filename: product-{id}-{index}.jpg
      const extension = image.name.split('.').pop() || 'jpg'
      const filename = `product-${productId}-${imageIndex}.${extension}`
      const filepath = path.join(uploadDir, filename)

      await writeFile(filepath, buffer)
      uploadedFilenames.push(filename)
      imageIndex++
    }

    return NextResponse.json({
      success: true,
      images: uploadedFilenames,
      message: `Successfully uploaded ${uploadedFilenames.length} images`
    })
  } catch (error) {
    console.error('Error uploading images:', error)
    return NextResponse.json(
      { error: 'Failed to upload images' },
      { status: 500 }
    )
  }
}

async function getExistingImageCount(productId: number): Promise<number> {
  try {
    const productsPath = path.join(process.cwd(), 'data', 'products.json')
    const fs = require('fs')
    const products = JSON.parse(fs.readFileSync(productsPath, 'utf8'))
    const product = products.find((p: any) => p.id === productId)
    return product?.images?.length || 0
  } catch {
    return 0
  }
}

