import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { checkAdminAuth } from '@/lib/auth-check'
import { validatePrice, validateStock, validateRequired, ValidationError } from '@/lib/validation'

// POST /api/admin/products - Create a new product (Admin only)
export async function POST(request: Request) {
  const authError = await checkAdminAuth()
  if (authError) return authError

  try {
    const body = await request.json()

    // Validate required fields
    validateRequired(body.name, 'Product name')
    validateRequired(body.category, 'Category')
    validateRequired(body.shortDescription, 'Short description')
    validateRequired(body.description, 'Description')

    // Validate price and stock
    const price = validatePrice(body.price)
    const salePrice = body.salePrice ? validatePrice(body.salePrice) : null
    const stock = validateStock(body.stock)

    // Validate sale price is less than regular price
    if (salePrice !== null && salePrice >= price) {
      throw new ValidationError('Sale price must be less than regular price')
    }

    const product = await prisma.product.create({
      data: {
        name: body.name,
        price,
        salePrice,
        category: body.category,
        subcategory: body.subcategory || '',
        shortDescription: body.shortDescription,
        description: body.description,
        images: body.images || [],
        isNew: body.isNew || false,
        isUsed: body.isUsed || false,
        condition: body.condition || null,
        stock,
        brand: body.brand || null,
        specs: body.specs || null,
        colors: body.colors || null,
        sizes: body.sizes || null,
      },
    })

    return NextResponse.json(product, { status: 201 })
  } catch (error) {
    console.error('Error creating product:', error)
    if (error instanceof ValidationError) {
      return NextResponse.json({ error: error.message }, { status: 400 })
    }
    return NextResponse.json({ error: 'Failed to create product' }, { status: 500 })
  }
}
