import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ code: string }> }
) {
  try {
    const { code } = await params

    const product = await db.product.findFirst({
      where: {
        OR: [
          { code },
          { slug: code },
        ]
      },
      include: { category: true },
    })

    if (!product) {
      return NextResponse.json(
        { status: 'error', message: 'Produto não encontrado' },
        { status: 404 }
      )
    }

    // Get related products (same category, excluding current)
    const related = await db.product.findMany({
      where: {
        categoryId: product.categoryId,
        NOT: { id: product.id },
      },
      include: { category: true },
      take: 6,
      orderBy: { isBestseller: 'desc' },
    })

    return NextResponse.json({
      status: 'success',
      data: { product, related },
    })
  } catch (error) {
    console.error('Error fetching product:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao buscar produto' },
      { status: 500 }
    )
  }
}
