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

// GET /api/reviews?reviewType=house&referenceId=xxx
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const reviewType = searchParams.get('reviewType');
    const referenceId = searchParams.get('referenceId');

    if (!reviewType || !referenceId) {
      return NextResponse.json(
        { error: 'reviewType and referenceId are required' },
        { status: 400 }
      );
    }

    const reviews = await db.review.findMany({
      where: { reviewType, referenceId },
      orderBy: { createdAt: 'desc' },
    });

    // Get user info for each review
    const reviewsWithUser = await Promise.all(
      reviews.map(async (review) => {
        const user = await db.user.findUnique({
          where: { id: review.userId },
          select: { id: true, name: true, avatar: true },
        });
        return {
          ...review,
          userName: user?.name || 'Unknown',
          userAvatar: user?.avatar || null,
        };
      })
    );

    const totalReviews = reviews.length;
    const averageRating = totalReviews > 0
      ? Math.round((reviews.reduce((sum, r) => sum + r.rating, 0) / totalReviews) * 10) / 10
      : 0;

    return NextResponse.json({
      reviews: reviewsWithUser,
      averageRating,
      totalReviews,
    });
  } catch (error) {
    console.error('Failed to fetch reviews:', error);
    return NextResponse.json(
      { error: 'Failed to fetch reviews' },
      { status: 500 }
    );
  }
}

// POST /api/reviews
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userId, rating, comment, reviewType, referenceId } = body;

    if (!userId || !rating || !reviewType || !referenceId) {
      return NextResponse.json(
        { error: 'userId, rating, reviewType, and referenceId are required' },
        { status: 400 }
      );
    }

    if (rating < 1 || rating > 5) {
      return NextResponse.json(
        { error: 'Rating must be between 1 and 5' },
        { status: 400 }
      );
    }

    // Check if user already reviewed this item
    const existingReview = await db.review.findFirst({
      where: { userId, reviewType, referenceId },
    });

    if (existingReview) {
      // Update existing review
      const updated = await db.review.update({
        where: { id: existingReview.id },
        data: { rating, comment: comment || null },
      });
      return NextResponse.json({ review: updated, updated: true });
    }

    const review = await db.review.create({
      data: {
        userId,
        rating,
        comment: comment || null,
        reviewType,
        referenceId,
      },
    });

    return NextResponse.json({ review, created: true }, { status: 201 });
  } catch (error) {
    console.error('Failed to create review:', error);
    return NextResponse.json(
      { error: 'Failed to create review' },
      { status: 500 }
    );
  }
}
