import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { ModerationStatus } from '@prisma/client'
import DOMPurify from 'isomorphic-dompurify'

const createSchema = z.object({
  rating: z.number().int().min(1).max(5),
  body: z.string().min(10).max(1000),
})

export async function GET(_req: NextRequest, { params }: { params: { id: string } }) {
  const reviews = await prisma.review.findMany({
    where: { spotId: params.id, status: ModerationStatus.APPROVED },
    orderBy: { createdAt: 'desc' },
    take: 20,
    include: { author: { select: { id: true, name: true, image: true } } },
  })
  return NextResponse.json({ reviews })
}

export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) return NextResponse.json({ error: 'Não autenticado' }, { status: 401 })

  const body = await req.json().catch(() => null)
  if (!body) return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })

  const parsed = createSchema.safeParse(body)
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 422 })

  const existing = await prisma.review.findFirst({
    where: { spotId: params.id, authorId: session.user.id },
  })
  if (existing) return NextResponse.json({ error: 'Já avaliaste este spot' }, { status: 409 })

  const review = await prisma.review.create({
    data: {
      spotId: params.id,
      authorId: session.user.id,
      rating: parsed.data.rating,
      body: DOMPurify.sanitize(parsed.data.body),
      status: 'PENDING',
    },
    select: { id: true, rating: true, status: true },
  })

  return NextResponse.json({ review }, { status: 201 })
}
