import { NextRequest, NextResponse } from 'next/server'
import { unlink } from 'fs/promises'
import path from 'path'
import fs from 'fs'

export async function POST(request: NextRequest) {
  try {
    const { productId, imageFilename } = await request.json()

    if (!productId || !imageFilename) {
      return NextResponse.json(
        { error: 'Product ID and image filename are required' },
        { status: 400 }
      )
    }

    // Delete image file
    const imagePath = path.join(process.cwd(), 'public', 'images', 'products', imageFilename)
    
    try {
      await unlink(imagePath)
    } catch (error: any) {
      // If file doesn't exist, that's okay - continue to remove from JSON
      if (error.code !== 'ENOENT') {
        console.error('Error deleting image file:', error)
      }
    }

    // Remove image from products.json
    const productsPath = path.join(process.cwd(), 'data', 'products.json')
    const products = JSON.parse(fs.readFileSync(productsPath, 'utf8'))
    
    const updatedProducts = products.map((p: any) => {
      if (p.id === productId) {
        return {
          ...p,
          images: p.images.filter((img: string) => img !== imageFilename)
        }
      }
      return p
    })

    fs.writeFileSync(productsPath, JSON.stringify(updatedProducts, null, 2), 'utf8')

    return NextResponse.json({
      success: true,
      message: 'Image deleted successfully'
    })
  } catch (error) {
    console.error('Error deleting image:', error)
    return NextResponse.json(
      { error: 'Failed to delete image' },
      { status: 500 }
    )
  }
}

