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

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

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

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

    // Verify the bid exists and belongs to this project
    const bid = await prisma.bid.findUnique({
      where: { id: bidId },
      select: {
        id: true,
        projectId: true,
        freelancerId: true,
        status: true
      }
    });

    if (!bid || bid.projectId !== projectId) {
      return NextResponse.json(
        { error: 'Bid not found' },
        { status: 404 }
      );
    }

    // Check if bid is still pending
    if (bid.status !== 'PENDING') {
      return NextResponse.json(
        { error: 'This bid has already been processed.' },
        { status: 400 }
      );
    }

    // Use transaction to ensure data consistency
    const result = await prisma.$transaction(async (tx) => {
      // Reject the bid
      const rejectedBid = await tx.bid.update({
        where: { id: bidId },
        data: { status: 'REJECTED' }
      });

      // Create notification for the rejected freelancer
      await tx.notification.create({
        data: {
          userId: bid.freelancerId,
          type: 'BID_REJECTED',
          title: 'Bid Rejected',
          message: `Unfortunately, your bid was not selected for this project.`,
          data: JSON.stringify({
            projectId: projectId,
            bidId: bidId
          })
        }
      });

      return rejectedBid;
    });

    return NextResponse.json({
      success: true,
      message: 'Bid rejected successfully',
      data: result
    });

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