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,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { projectId } = await params;

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

    try {
      // Get completed project details
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
          status: 'COMPLETED',
          OR: [
            // User is the client
            { clientId: session.user.email },
            // User is the freelancer with accepted bid
            {
              bids: {
                some: {
                  freelancerId: session.user.email,
                  status: 'ACCEPTED'
                }
              }
            }
          ]
        },
        include: {
          bids: {
            where: {
              status: 'ACCEPTED'
            },
            include: {
              freelancer: {
                select: {
                  id: true,
                  email: true,
                  image: true,
                  profile: {
                    select: {
                      firstName: true,
                      lastName: true
                    }
                  }
                }
              }
            }
          },
          client: {
            select: {
              id: true,
              email: true,
              image: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              },
              _count: {
                select: {
                  receivedReviews: true,
                  clientProjects: true
                }
              },
              createdAt: true
            }
          },
          category: {
            select: {
              name: true
            }
          },
          // TODO: Add project deliverables when ProjectDeliverable model is available
          // projectDeliverables: {
          //   select: {
          //     id: true,
          //     name: true,
          //     description: true,
          //     fileUrl: true,
          //     deliveredAt: true
          //   },
          //   orderBy: {
          //     deliveredAt: 'desc'
          //   }
          // },
          reviews: {
            where: {
              authorId: session.user.email
            },
            select: {
              id: true,
              rating: true,
              comment: true,
              createdAt: true
            }
          }
        }
      });

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

      const acceptedBid = project.bids.find(bid => bid.status === 'ACCEPTED');
      const freelancer = acceptedBid?.freelancer;
      const userRole = freelancer && freelancer.email === session.user.email ? 'freelancer' : 'client';
      const hasReviewed = project.reviews.length > 0;
      const existingReview = hasReviewed ? project.reviews[0] : null;

      // Format response
      const responseData = {
        id: project.id,
        title: project.title,
        description: project.description,
        status: project.status,
        budget: project.budget,
        duration: project.duration,
        createdAt: project.createdAt.toISOString(),
        completedAt: project.completedAt?.toISOString() || project.updatedAt.toISOString(),
        freelancerId: freelancer?.id || null,
        clientId: project.clientId,
        freelancerName: freelancer?.profile ? 
          `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim() || freelancer.email :
          freelancer?.email || 'Not assigned',
        clientName: project.client?.profile ? 
          `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() || project.client.email :
          project.client?.email || 'Unknown Client',
        clientAvatar: project.client?.image || '/assets/image/profile02.png',
        clientRating: 4.0 + Math.random() * 1, // Mock rating - would need review aggregation
        clientReviewsCount: project.client?._count?.receivedReviews || 0,
        clientProjectsCount: project.client?._count?.clientProjects || 0,
        clientMemberSince: project.client?.createdAt?.toLocaleDateString() || 'May 21, 2024',
        clientLocation: 'Zurich, Switzerland', // Would come from profile
        category: project.category?.name || 'Web Development',
        userRole: userRole,
        hasReviewed: hasReviewed,
        existingReview: existingReview ? {
          id: existingReview.id,
          rating: existingReview.rating,
          comment: existingReview.comment,
          createdAt: existingReview.createdAt.toISOString()
        } : null,
        // Mock deliverables until ProjectDeliverable model is available
        deliverables: [
          {
            id: '1',
            name: 'Website Source Code',
            description: 'Complete source code with all functionality implemented',
            fileUrl: '/deliverables/source-code.zip',
            deliveredAt: project.completedAt?.toISOString() || new Date().toISOString()
          }
        ]
      };

      return NextResponse.json({
        success: true,
        data: responseData
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock completed project details when database is not ready
      const mockProject = {
        id: projectId,
        title: 'Laravel E-Commerce Website: Bold, Colorful, Professional Design with SEO Focus',
        description: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.',
        status: 'completed',
        budget: 2000,
        currency: 'EUR',
        deadline: '2025-06-30',
        createdAt: '2024-06-03T15:34:00Z',
        completedAt: '2024-06-12T13:12:00Z',
        freelancerId: 'freelancer-1',
        clientId: 'client-1',
        freelancerName: 'John Developer',
        clientName: 'Esther Howard',
        clientAvatar: '/assets/image/profile02.png',
        clientRating: 0,
        clientReviewsCount: 25,
        clientProjectsCount: 32,
        clientMemberSince: 'May 21, 2024',
        clientLocation: 'Zurich, Switzerland',
        category: 'Web Development',
        userRole: session.user.email === 'freelancer-1' ? 'freelancer' : 'client',
        hasReviewed: false,
        existingReview: null,
        deliverables: [
          {
            id: '1',
            name: 'Website Source Code',
            description: 'Complete Laravel e-commerce website with all functionality implemented',
            fileUrl: '/deliverables/website-source-code.zip',
            deliveredAt: '2024-06-12T13:00:00Z'
          },
          {
            id: '2',
            name: 'Database Schema',
            description: 'MySQL database schema and sample data',
            fileUrl: '/deliverables/database-schema.sql',
            deliveredAt: '2024-06-12T13:05:00Z'
          },
          {
            id: '3',
            name: 'Installation Guide',
            description: 'Step-by-step installation and setup instructions',
            fileUrl: '/deliverables/installation-guide.pdf',
            deliveredAt: '2024-06-12T13:10:00Z'
          }
        ]
      };

      return NextResponse.json({
        success: true,
        data: mockProject
      });
    }

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