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

export const GET = withAuth(async (request: NextRequest, user) => {
  try {
    const products = await readProductsFromFile()
    return NextResponse.json({ products })
  } catch (error) {
    console.error('Error fetching products:', error)
    return NextResponse.json(
      { message: 'Failed to fetch products' },
      { status: 500 }
    )
  }
})

export const POST = withAuth(async (request: NextRequest, user) => {
  try {
    const productData = await request.json()

    // Validate required fields
    const { name, description, price } = productData
    if (!name || !description || !price) {
      return NextResponse.json(
        { message: 'Name, description, and price are required' },
        { status: 400 }
      )
    }

    // Set defaults for optional fields
    const newProductData = {
      name,
      description,
      price,
      images: productData.images || [],
      videoUrl: productData.videoUrl || null,
      featured: productData.featured || false,
    }

    const newProduct = await createProduct(newProductData)

    return NextResponse.json(
      { message: 'Product created successfully', product: newProduct },
      { status: 201 }
    )
  } catch (error: any) {
    console.error('Error creating product:', error)
    return NextResponse.json(
      { message: error.message || 'Failed to create product' },
      { status: 500 }
    )
  }
})
