import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'

export const dynamic = 'force-dynamic'

// GET: Fetch reviews for a product
// Query params: ?vipProductId=xxx OR ?digitalProductId=xxx
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const vipProductId = searchParams.get('vipProductId')
    const digitalProductId = searchParams.get('digitalProductId')

    const where: any = {}
    if (vipProductId) where.vipProductId = vipProductId
    else if (digitalProductId) where.digitalProductId = digitalProductId
    else return NextResponse.json({ error: 'productId diperlukan' }, { status: 400 })

    const reviews = await prisma.review.findMany({
      where,
      include: {
        user: { select: { name: true, image: true } }
      },
      orderBy: { createdAt: 'desc' },
      take: 20,
    })

    const avgRating = reviews.length > 0
      ? reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length
      : 0

    return NextResponse.json({ reviews, avgRating: Math.round(avgRating * 10) / 10, total: reviews.length })
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}

// POST: Submit a review (only for SUCCESS orders)
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

    const body = await req.json()
    const { orderId, rating, comment } = body

    if (!orderId) return NextResponse.json({ error: 'orderId diperlukan' }, { status: 400 })
    if (!rating || rating < 1 || rating > 5) return NextResponse.json({ error: 'Rating harus 1-5' }, { status: 400 })

    // Verify order belongs to user and is SUCCESS
    const order = await prisma.order.findFirst({
      where: { id: orderId, userId: session.user.id, status: 'SUCCESS' },
    })

    if (!order) return NextResponse.json({ error: 'Order tidak ditemukan atau belum selesai' }, { status: 404 })

    // Check if already reviewed
    const existing = await prisma.review.findUnique({ where: { orderId } })
    if (existing) return NextResponse.json({ error: 'Kamu sudah memberikan ulasan untuk pesanan ini' }, { status: 400 })

    const review = await prisma.review.create({
      data: {
        userId: session.user.id,
        orderId,
        rating,
        comment: comment || null,
        vipProductId: order.vipProductId || null,
        digitalProductId: order.digitalProductId || null,
      },
    })

    return NextResponse.json({ success: true, review })
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
