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

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get user ID from email
    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
      select: { id: true }
    });

    if (!user) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      );
    }

    try {
      // Fetch all reviews where this user is the recipient (freelancer being reviewed)
      const reviews = await prisma.review.findMany({
        where: {
          recipientId: user.id
        },
        select: {
          id: true,
          rating: true,
          comment: true,
          createdAt: true,
          author: {
            select: {
              id: true,
              email: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          },
          project: {
            select: {
              id: true,
              title: true
            }
          }
        },
        orderBy: {
          createdAt: 'desc'
        }
      });

      // Calculate average rating and review count
      const totalReviews = reviews.length;
      let averageRating = 0;

      if (totalReviews > 0) {
        const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0);
        averageRating = totalRating / totalReviews;
      }

      // Round to 1 decimal place
      averageRating = Math.round(averageRating * 10) / 10;

      return NextResponse.json({
        success: true,
        data: {
          averageRating,
          totalReviews,
          reviews: reviews.map(review => ({
            id: review.id,
            rating: review.rating,
            comment: review.comment,
            createdAt: review.createdAt,
            author: {
              id: review.author.id,
              name: review.author.profile 
                ? `${review.author.profile.firstName || ''} ${review.author.profile.lastName || ''}`.trim()
                : review.author.email,
            },
            project: {
              id: review.project.id,
              title: review.project.title
            }
          }))
        }
      });

    } catch (dbError) {
      console.error('Database error fetching ratings:', dbError);

      return NextResponse.json(
        {
          error: 'Failed to fetch ratings from database',
          type: 'database_error'
        },
        { status: 503 }
      );
    }

  } catch (error) {
    console.error('Error fetching ratings:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch ratings',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}