import { NextResponse } from 'next/server'
import { Prisma } from '@prisma/client'
import { prisma } from '@/lib/prisma'
import { checkAdminAuth } from '@/lib/auth-check'
import { validateRating, validateReviewStatus, ValidationError } from '@/lib/validation'

type Params = {
  params: Promise<{
    id: string
  }>
}

// PUT /api/admin/reviews/[id] - Update review (Admin only)
export async function PUT(request: Request, { params }: Params) {
  const authError = await checkAdminAuth()
  if (authError) return authError

  try {
    const { id } = await params
    const body = await request.json()

    // Build update data object - only include provided fields with validation
    const updateData: Prisma.ReviewUpdateInput = {}
    if (body.status !== undefined) {
      updateData.status = validateReviewStatus(body.status)
    }
    if (body.author !== undefined) updateData.author = body.author
    if (body.rating !== undefined) {
      updateData.rating = validateRating(body.rating)
    }
    if (body.text !== undefined) updateData.text = body.text

    const review = await prisma.review.update({
      where: { id },
      data: updateData,
    })

    return NextResponse.json(review)
  } catch (error) {
    console.error('Error updating review:', error)
    if (error instanceof ValidationError) {
      return NextResponse.json({ error: error.message }, { status: 400 })
    }
    return NextResponse.json({ error: 'Failed to update review' }, { status: 500 })
  }
}

// DELETE /api/admin/reviews/[id] - Delete a review (Admin only)
export async function DELETE(request: Request, { params }: Params) {
  const authError = await checkAdminAuth()
  if (authError) return authError

  try {
    const { id } = await params

    await prisma.review.delete({
      where: { id },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting review:', error)
    return NextResponse.json({ error: 'Failed to delete review' }, { status: 500 })
  }
}
