import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

export async function POST(request: NextRequest) {
  try {
    const { productId } = await request.json()

    if (!productId) {
      return NextResponse.json(
        { error: 'Product ID is required' },
        { status: 400 }
      )
    }

    // Load products from JSON
    const productsPath = path.join(process.cwd(), 'data', 'products.json')
    const products = JSON.parse(fs.readFileSync(productsPath, 'utf8'))

    // Find product to delete
    const productToDelete = products.find((p: any) => p.id === productId)
    if (!productToDelete) {
      return NextResponse.json(
        { error: 'Product not found' },
        { status: 404 }
      )
    }

    // Delete associated images
    if (productToDelete.images && productToDelete.images.length > 0) {
      const imagesDir = path.join(process.cwd(), 'public', 'images', 'products')
      productToDelete.images.forEach((imgFilename: string) => {
        const imagePath = path.join(imagesDir, imgFilename)
        try {
          if (fs.existsSync(imagePath)) {
            fs.unlinkSync(imagePath)
          }
        } catch (error) {
          console.error(`Error deleting image ${imgFilename}:`, error)
          // Continue even if image deletion fails
        }
      })
    }

    // Remove product from array
    const updatedProducts = products.filter((p: any) => p.id !== productId)

    // Save updated products
    fs.writeFileSync(productsPath, JSON.stringify(updatedProducts, null, 2), 'utf8')

    return NextResponse.json({
      success: true,
      message: 'Product deleted successfully',
      deletedImages: productToDelete.images?.length || 0
    })
  } catch (error) {
    console.error('Error deleting product:', error)
    return NextResponse.json(
      { error: 'Failed to delete product' },
      { status: 500 }
    )
  }
}

