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; freelancerId: string }> }
) {
  try {
    const { projectId, freelancerId } = await params;
    
    // Get session to verify access
    const session = await getServerSession(authOptions);
    if (!session) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    if (!projectId || !freelancerId) {
      return NextResponse.json(
        { error: 'Project ID and Freelancer ID are required' },
        { status: 400 }
      );
    }

    // Verify the project exists and user has access
    const project = await prisma.project.findUnique({
      where: { id: projectId },
      select: {
        id: true,
        title: true,
        clientId: 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 bid information.' },
        { status: 403 }
      );
    }

    // Get the bid for this freelancer on this project
    const bid = await prisma.bid.findFirst({
      where: {
        projectId: projectId,
        freelancerId: freelancerId
      },
      include: {
        freelancer: {
          select: {
            id: true,
            email: true,
            profile: {
              select: {
                firstName: true,
                lastName: true
              }
            }
          }
        }
      }
    });

    if (!bid) {
      return NextResponse.json(
        { error: 'No bid found for this freelancer on this project' },
        { status: 404 }
      );
    }

    // Format freelancer name
    const freelancerName = bid.freelancer.profile?.firstName && bid.freelancer.profile?.lastName
      ? `${bid.freelancer.profile.firstName} ${bid.freelancer.profile.lastName}`
      : bid.freelancer.email;

    const bidInfo = {
      id: bid.id,
      amount: bid.amount,
      duration: bid.duration,
      status: bid.status,
      projectId: project.id,
      projectTitle: project.title,
      freelancerId: bid.freelancerId,
      freelancerName: freelancerName,
      createdAt: bid.createdAt.toISOString()
    };

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

  } catch (error) {
    console.error('Error fetching bid info:', error);
    
    let errorMessage = 'An unexpected error occurred while fetching bid information.';
    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 or freelancer 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 }
    );
  }
}