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

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const { searchParams } = new URL(req.url);
    
    // Get session to verify access
    const session = await getServerSession(authOptions);
    if (!session) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get filters from query parameters
    const filters: BidFilters = {
      search: searchParams.get('search') || '',
      location: searchParams.get('location') || '',
      rating: searchParams.get('rating') || '',
      sortBy: (searchParams.get('sortBy') as BidFilters['sortBy']) || 'newest'
    };

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

    // First verify the project exists and user has access (is the client)
    const project = await prisma.project.findUnique({
      where: { id: projectId },
      select: {
        id: true,
        title: true,
        clientId: true,
        client: {
          select: {
            id: true,
            email: true
          }
        }
      }
    });

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

    // Check if current user is the client of this project
    if (project.clientId !== session.user?.id) {
      return NextResponse.json(
        { error: 'Access denied. Only the project client can view bids.' },
        { status: 403 }
      );
    }

    // Build where clause for filtering
    const whereClause: any = {
      projectId: projectId
    };

    // Filter by freelancer name or location if search is provided
    if (filters.search) {
      whereClause.freelancer = {
        OR: [
          {
            profile: {
              OR: [
                { firstName: { contains: filters.search } },
                { lastName: { contains: filters.search } }
              ]
            }
          },
          { email: { contains: filters.search } }
        ]
      };
    }

    // Filter by location
    if (filters.location) {
      if (!whereClause.freelancer) whereClause.freelancer = {};
      whereClause.freelancer.profile = {
        country: {
          name: { contains: filters.location }
        }
      };
    }

    // Get bids with freelancer details
    let bids = await prisma.bid.findMany({
      where: whereClause,
      include: {
        freelancer: {
          select: {
            id: true,
            email: true,
            image: true,
            profile: {
              select: {
                firstName: true,
                lastName: true,
                phone: true,
                city: true,
                country: {
                  select: {
                    name: true
                  }
                }
              }
            },
            _count: {
              select: {
                receivedReviews: true
              }
            }
          }
        }
      }
    });

    // Calculate average rating for each freelancer and filter by rating if specified
    const bidsWithRating = await Promise.all(
      bids.map(async (bid) => {
        const avgRating = await prisma.review.aggregate({
          where: { recipientId: bid.freelancerId },
          _avg: { rating: true }
        });

        const averageRating = avgRating._avg.rating || 0;

        // Apply rating filter
        if (filters.rating && averageRating < parseFloat(filters.rating)) {
          return null;
        }

        return {
          ...bid,
          freelancer: {
            ...bid.freelancer,
            averageRating
          }
        };
      })
    );

    // Remove filtered out bids
    const validBids = bidsWithRating.filter(bid => bid !== null);

    // Sort bids based on sortBy parameter
    let sortedBids = [...validBids];
    switch (filters.sortBy) {
      case 'newest':
        sortedBids.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        break;
      case 'oldest':
        sortedBids.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
        break;
      case 'price_low':
        sortedBids.sort((a, b) => a.amount - b.amount);
        break;
      case 'price_high':
        sortedBids.sort((a, b) => b.amount - a.amount);
        break;
      case 'rating':
        sortedBids.sort((a, b) => b.freelancer.averageRating - a.freelancer.averageRating);
        break;
      default:
        break;
    }

    const responseData = {
      projectId: project.id,
      projectTitle: project.title,
      bids: sortedBids,
      totalBids: sortedBids.length
    };

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

  } catch (error) {
    console.error('Error fetching project bids:', error);
    
    let errorMessage = 'An unexpected error occurred while fetching bids.';
    let details = 'Unknown error';
    
    if (error instanceof Error) {
      details = error.message;
      
      if (error.message.includes('connect') || error.message.includes('ECONNREFUSED')) {
        errorMessage = 'Database connection failed. Please contact support if this persists.';
      } else if (error.message.includes('not found') || error.message.includes('P2025')) {
        errorMessage = 'The requested project was not found.';
      } else if (error.message.includes('timeout')) {
        errorMessage = 'Request timed out. Please try again.';
      }
    }
    
    return NextResponse.json(
      { 
        error: errorMessage,
        details: details
      },
      { status: 500 }
    );
  }
}
