import { NextRequest, NextResponse } from 'next/server';
import { createReview, getProductReviews, getReviews, saveReviews } from '@/lib/db';

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const productId = searchParams.get('productId');
  const all = searchParams.get('all');

  if (all === 'true') {
    return NextResponse.json({ success: true, reviews: getReviews() });
  }
  if (!productId) return NextResponse.json({ success: false, message: 'productId required' }, { status: 400 });
  return NextResponse.json({ success: true, reviews: getProductReviews(productId) });
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { productId, userId, userName, rating, comment } = body;
    if (!productId || !rating || !comment || rating < 1 || rating > 5) {
      return NextResponse.json({ success: false, message: 'Invalid review data' }, { status: 400 });
    }
    const review = createReview({ productId, userId: userId || 'guest', userName: userName || 'Anonymous', rating, comment, status: 'approved' });
    return NextResponse.json({ success: true, review });
  } catch (e: any) {
    return NextResponse.json({ success: false, message: e.message }, { status: 500 });
  }
}

export async function PATCH(req: NextRequest) {
  const body = await req.json();
  const { id, status } = body;
  const reviews = getReviews();
  const idx = reviews.findIndex(r => r.id === id);
  if (idx === -1) return NextResponse.json({ success: false, message: 'Not found' }, { status: 404 });
  reviews[idx].status = status;
  saveReviews(reviews);
  return NextResponse.json({ success: true });
}
