import { NextRequest, NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth'
import { readProductsFromFile, updateProduct, deleteProduct } from '@/lib/products'

export const GET = withAuth(async (request: NextRequest, user: any, { params }: { params: { slug: string } }) => {
  try {
    const products = await readProductsFromFile()
    const product = products.find(p => p.slug === params.slug)

    if (!product) {
      return NextResponse.json(
        { message: 'Product not found' },
        { status: 404 }
      )
    }

    return NextResponse.json({ product })
  } catch (error) {
    console.error('Error fetching product:', error)
    return NextResponse.json(
      { message: 'Failed to fetch product' },
      { status: 500 }
    )
  }
})

export const PUT = withAuth(async (request: NextRequest, user: any, { params }: { params: { slug: string } }) => {
  try {
    const slug = params.slug
    if (!slug) {
      return NextResponse.json(
        { message: 'Invalid product slug' },
        { status: 400 }
      )
    }

    const productData = await request.json()

    const updatedProduct = await updateProduct(slug, productData)

    if (!updatedProduct) {
      return NextResponse.json(
        { message: 'Product not found' },
        { status: 404 }
      )
    }

    return NextResponse.json({
      message: 'Product updated successfully',
      product: updatedProduct
    })
  } catch (error: any) {
    console.error('Error updating product:', error)
    return NextResponse.json(
      { message: error.message || 'Failed to update product' },
      { status: 500 }
    )
  }
})

export const DELETE = withAuth(async (request: NextRequest, user: any, { params }: { params: { slug: string } }) => {
  try {
    const slug = params.slug
    if (!slug) {
      return NextResponse.json(
        { message: 'Invalid product slug' },
        { status: 400 }
      )
    }

    const deleted = await deleteProduct(slug)

    if (!deleted) {
      return NextResponse.json(
        { message: 'Product not found' },
        { status: 404 }
      )
    }

    return NextResponse.json({ message: 'Product deleted successfully' })
  } catch (error) {
    console.error('Error deleting product:', error)
    return NextResponse.json(
      { message: 'Failed to delete product' },
      { status: 500 }
    )
  }
})
