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(
  request: NextRequest,
  { params }: { params: { projectId: string } }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const user = session.user as any;
    const { projectId } = params;
    const { searchParams } = new URL(request.url);
    const freelancerId = searchParams.get('freelancerId');

    if (!projectId) {
      return NextResponse.json(
        { error: 'Project ID is required' },
        { status: 400 }
      );
    }

    if (!freelancerId) {
      return NextResponse.json(
        { error: 'Freelancer ID is required' },
        { status: 400 }
      );
    }

    // Verify user is the client of this project
    const project = await prisma.project.findFirst({
      where: {
        id: projectId,
        clientId: user.id,
        status: 'COMPLETED'
      },
      include: {
        client: {
          include: {
            profile: true
          }
        },
        category: {
          select: {
            name: true,
            icon: true
          }
        },
        bids: {
          where: {
            freelancerId: freelancerId,
            status: 'ACCEPTED'
          },
          include: {
            freelancer: {
              include: {
                profile: true,
                _count: {
                  select: {
                    receivedReviews: true
                  }
                }
              }
            }
          }
        }
      }
    });

    if (!project) {
      return NextResponse.json(
        { error: 'Completed project not found or access denied' },
        { status: 404 }
      );
    }

    const acceptedBid = project.bids[0];
    if (!acceptedBid) {
      return NextResponse.json(
        { error: 'No accepted freelancer found for this project' },
        { status: 404 }
      );
    }

    // Get freelancer rating
    const freelancerReviews = await prisma.review.aggregate({
      where: { recipientId: acceptedBid.freelancer.id },
      _avg: { rating: true },
      _count: { rating: true }
    });

    // Check if review already exists
    const existingReview = await prisma.review.findFirst({
      where: {
        projectId: projectId,
        authorId: user.id,
        recipientId: acceptedBid.freelancer.id
      }
    });

    if (existingReview) {
      return NextResponse.json(
        { error: 'You have already reviewed this project' },
        { status: 400 }
      );
    }

    const transformedProject = {
      id: project.id,
      title: project.title,
      description: project.description,
      budget: project.budget,
      completedAt: project.completedAt?.toISOString() || project.updatedAt.toISOString(),
      category: {
        name: project.category?.name || 'General',
        icon: project.category?.icon || '/assets/image/cabinetmaking.svg'
      },
      freelancer: {
        id: acceptedBid.freelancer.id,
        name: acceptedBid.freelancer.profile 
          ? `${acceptedBid.freelancer.profile.firstName || ''} ${acceptedBid.freelancer.profile.lastName || ''}`.trim() || acceptedBid.freelancer.email
          : acceptedBid.freelancer.email || 'Unknown Freelancer',
        profileImage: acceptedBid.freelancer.image || '/assets/image/user.png',
        rating: freelancerReviews._avg.rating || 0,
        reviewCount: freelancerReviews._count.rating || 0
      }
    };

    return NextResponse.json({
      success: true,
      project: transformedProject
    });

  } catch (error) {
    console.error('Error fetching project review details:', error);
    return NextResponse.json(
      { 
        success: false,
        error: 'Internal server error' 
      },
      { status: 500 }
    );
  }
}